我想将图像从一个活动传递到另一个活动,这是我的代码:
public boolean launchCamera(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo;
try {
// place where to store camera taken picture
photo = this.createTemporaryFile("picture", ".jpg");
photo.delete();
} catch (Exception e) {
Log.v(TAG, "Can't create file to take picture!");
Toast.makeText(MainActivity.this, "Please check SD card! Image shot is impossible!", Toast.LENGTH_LONG);
return false;
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
//start camera intent
this.startActivityForResult(intent, MenuShootImage);
return true;
}
private File createTemporaryFile(String part, String ext) throws Exception {
File tempDir = Environment.getExternalStorageDirectory();
tempDir = new File(tempDir.getAbsolutePath() + "/.temp/");
if (!tempDir.exists()) {
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
public Bitmap grabImage()
{
this.getContentResolver().notifyChange(mImageUri, null);
ContentResolver cr = this.getContentResolver();
Bitmap bitmap=null;
try
{
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri);
}
catch (Exception e)
{
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Failed to load", e);
}
return bitmap;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
Intent imagepass = null;
Bitmap bitmap = null;
if(requestCode == MenuShootImage && resultCode == RESULT_OK)
{
bitmap = this.grabImage();
imagepass = new Intent(this,MainActivity2.class);
imagepass.putExtra("imagepass", bitmap );
startActivity(imagepass);
}
}
问题是,我根本无法访问其他活动,在调试模式下,我可以访问startactivity(imagepass)行;不要去参加主要活动2。有人能帮我吗?
首先,如果你真的想通过Intent传递位图,你需要先将其转换为Byte Array,因为位图不能像那样通过Intent附加。
以下是如何做到这一点https://stackoverflow.com/a/11010565/4651112
但根据最佳实践,我建议您根本不要通过意图发送位图。发送文件名图像,并让目标"活动"从文件中对其进行解码。好多了。
1)首先将图像转换为字节数组,然后传递到Intent,在下一个活动中从Bundle获取字节数组并转换为图像(位图)并设置到ImageView。
将位图转换为字节数组:-
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
将字节数组传递到意图:-
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);
从束中获取字节数组并转换为位图图像:-
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bmp);
2) 首先将图像保存到SDCard中,然后在下一个活动中将此图像设置到ImageView中。
3) 将位图传递到Intent中,并在捆绑包的下一个活动中获取位图,但问题是,如果此时位图/图像大小较大,则图像不会在下一活动中加载