在将其添加到 intent、发送出去并解码之前,将它转换为字节数组。
//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);
然后在第二个Activity中:
byte[] byteArray = getIntent().getByteArrayExtra("image")
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length)
编辑
我觉得应该更新这篇文章,分享最佳实践:
在你的第一个活动中,你应该将位图保存到磁盘上,然后在下一个活动中重新加载它。确保在第一个活动中回收位图以便进行垃圾回收:
活动1:
try {
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
bmp.recycle();
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
在第二个Activity中,加载位图:
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();
}