user9578576
user9578576

Reputation:

transferring bitmap between activities

bmp1 is a bitmap image

in activity 1 I have the following code

ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bmp1.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
regIntent.putExtra("chosenImage",byteArray);

then in activity2 i do this.

Intent regIntent = getIntent();
 byte[] byteArray = regIntent.getByteArrayExtra("chosenImage");
        bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
        bmp = Bitmap.createScaledBitmap(bmp, 150, 200, true);

i then display the image using this code:

 ImageView mainBookImage = findViewById(R.id.mainBookImage); //uncoment to load image
        mainBookImage.setImageBitmap(bmp);

however i just end up getting a blank image, any ideas why?

Upvotes: 0

Views: 44

Answers (2)

Sagar
Sagar

Reputation: 24907

I would recommend you to implement different approach.

If its mandatory for you to pass the bitmap itself, then you can pass the Bitmap object as it is since it implements Parcelable. It would be as simple as regIntent.putExtra("chosenImage",bmp1); and in activity 2:

final Bitmap bmp1= regIntent.getParcelableExtra("chosenImage");

However, this approach is highly discouraged since it will cost a lot of memory and impact responsiveness of your application. Moreover on low end devices this could lead to crash due to lack of memory and also limitation on data size which could be transferred through Intents.

One approach could be to store it in a file and then pass the path of file through Intent extra. In Activity2 you can retrieve the path -> load the image in Bitmap -> use in ImageView.

Upvotes: 0

Nikunj Patel
Nikunj Patel

Reputation: 444

In your First Activity.

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp1.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent intent = new Intent();
intent.setClass(getApplicationContext(), MainActivity.class);
intent.putExtra("chosenImage", byteArray);
startActivity(n);

In your Second Activity oncreate()

Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("chosenImage");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

//  And Set Image in Imageview like this

ImageView mainBookImage = findViewById(R.id.mainBookImage);
if (bmp != null) {
        mainBookImage.setImageBitmap(bmp);
    }

Upvotes: 1

Related Questions