Lolization
Lolization

Reputation: 69

It seems that ImageView.setImageBitmap doesn't work

I have an activity in which you draw a bitmap, and use an intent to send it to the next Activity and put it in an ImageView in there. For some reason, it does not produce and error but also doesn't set the image to what it's supposed to be. Can this be an issue when having incompatible width and height?

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

Intent i = new Intent(getApplicationContext(), PrintActivity.class);
i.putExtra("bitmap", byteArray);
startActivity(i);

I just want to mention that this method works in other activies, as I send bitmaps across activities multiple times.

The activity that is getting the intent:

img = findViewById(R.id.img);

byte[] byteArray = getIntent().getByteArrayExtra("bitmap");
if (byteArray.length > 0) {
    Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    ImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // In a different thread this seemed to help the OP but it didn't in my case
    img.setImageBitmap(bmp);

I also tried to save the bitmap to gallery but it gave multiple errors, some indicating that the bitmap is empty. Although I do not see how this is the case because it is a bitmap of a canvas. I fetch it with this:

public Bitmap getBitmap() {
    return mBitmap;
}

And mbitmap is the one used to write on the canvas:

canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

What am I doing wrong?

Upvotes: 0

Views: 252

Answers (1)

I see you move around bitmaps by compressing to byte array, and then decoding them again. Please note that BitMaps implements Parcelable, which is nice, because you can put parcelables directly into intents with

Intent intentions = new Intent(this, someActivity.class);
intentions.putExtra("parcelable_photo", mPhoto);

To get a parcelable

Intent received = getIntent();
Bitmap mPhoto = (Bitmap) received.getExtras().getParcelable("parcelable_photo");

That should be faster and less typing work than your current method.

To set this bitmap in an imageview, the following should do the trick:

ImageView mImg = findViewById(R.id.img_id);
img.setImageBitmap(mPhoto);

Here is the source for setImageBitmap().

I do not know about ImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null), but I am hopeful that above methods should do the trick.

Please do not hesitate to comment if trouble remains

Upvotes: 1

Related Questions