adi*_*ean 66 android bitmap android-intent
我有一个bmp在Activity1中命名的Bitmap变量,我想将位图发送到Activity2
以下是我用来传递意图的代码.
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image",bmp);
startActivity(in1);
Run Code Online (Sandbox Code Playgroud)
在Activity2中,我尝试使用以下代码访问位图
Bundle ex = getIntent().getExtras();
Bitmap bmp2 = ex.getParceable("image");
ImageView result = (ImageView)findViewById(R.Id.imageView1);
result.setImageBitmap(bmp);
Run Code Online (Sandbox Code Playgroud)
应用程序运行时没有例外,但它没有给出预期的结果
Zai*_*ani 185
在将其添加到intent,将其发送并解码之前,将其转换为Byte数组.
//Convert to byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image",byteArray);
Run Code Online (Sandbox Code Playgroud)
然后在活动2中:
byte[] byteArray = getIntent().getByteArrayExtra("image");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Run Code Online (Sandbox Code Playgroud)
编辑
以为我应该用最佳实践更新这个:
在第一个活动中,您应该将位图保存到磁盘,然后在下一个活动中加载它.确保在第一个活动中回收您的位图以填充垃圾回收:
活动1:
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
在活动2中,加载位图:
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
干杯!
and*_*per 10
有时,位图可能对于编码和解码来说太大或者在intent中作为字节数组传递.这可能会导致OOM或错误的UI体验.
我建议考虑将位图放入新活动的静态变量(使用它的那个),当你不再需要它时,它将小心地为空(意味着在onDestroy中,但仅当"isChangingConfigurations"返回false时).
| 归档时间: |
|
| 查看次数: |
88051 次 |
| 最近记录: |