How to Pass a Bitmap Object from One Activity to Another

How can I pass a Bitmap object from one activity to another

Bitmap implements Parcelable, so you could always pass it with the intent:

Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);

and retrieve it on the other end:

Intent intent = getIntent(); 
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");

Passing Bitmap between two activities

You can simply try with below -

Intent i = new Intent(this, Second.class)
i.putExtra("Image", bitmap);
startActivity(i)

And, in Second.class

Bitmap bitmap = (Bitmap) intent.getParcelableExtra("Image");

Have a look at here If you want to compress your Bitmap before sending to next activity just have a look at below -

Intent i = new Intent(this, NextActivity.class);
Bitmap b; // your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);

in your nextactivity -

if(getIntent().hasExtra("byteArray")) {
ImageView previewThumbnail = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent()
.getByteArrayExtra("byteArray").length);
previewThumbnail.setImageBitmap(b);
}

How to pass object which contain Bitmap to another activity

Its not a great idea to pass Bitmap between two activities. You would get TransactionTooLargeException when you attempt to do so. Maximum limit for transaction data is around 1MB and Bitmap could easily overshoot it. This could lead to crash.

You can just use the URI that you are getting in onActivityResult() via following code:

Uri selectedImage = data.getData();

Pass this URI between the activities. You can then load image using the URI on-demand rather than transfering whole Bitmap object.

@SabaJafarzade Thank you pointing out, to reuse the Uri.

how do you pass images (bitmaps) between android activities using bundles?

I would highly recommend a different approach.

It's possible if you REALLY want to do it, but it costs a lot of memory and is also slow. It might not work if you have an older phone and a big bitmap. You could just pass it as an extra, for example intent.putExtra("data", bitmap). A Bitmap implements Parcelable, so you can put it in an extra. Likewise, a bundle has putParcelable.

If you want to pass it inbetween activities, I would store it in a file. That's more efficient, and less work for you. You can create private files in your data folder using MODE_PRIVATE that are not accessible to any other app.



Related Topics



Leave a reply



Submit