0

I'm creating a bitmap, but after that, I'm creating another one with a scale:

Bitmap originalBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.a1);
float ratio = (float) originalBitmap.getWidth() / originalBitmap.getHeight();
int h = sh/7;
int w = (int) (h * ratio);
scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, w, h, true);
originalBitmap.recycle();

It is safe to recycle originalBitmap after creating scaled Bitmap? The original bitmap will not be used, only the scaled Bitmap will be used.

I'm asking it because I had a comment in that line that tells about past "Recycled Bitmap" crashes, but I don't know in which circumstances. Maybe recycling the original one can generate crashes in the scaled version?

halfer
  • 19,824
  • 17
  • 99
  • 186
NullPointerException
  • 36,107
  • 79
  • 222
  • 382
  • I don't believe there should be any issue with recycling it, but I haven't done manual bitmap scaling in a while. – Martin Marconcini Oct 22 '19 at 15:19
  • @MartinMarconcini and how did you do it then? – NullPointerException Oct 22 '19 at 15:32
  • Considering we're in October 2019, and the last time I had to manually decode a bitmap like this was in 2014, I don't remember. But in general, what I see there is fine, like you are doing the "right" thing. The reason why this *may crash* -at least back then- is if the framework createScaledBitmap references your originalBitmap, even after it was created, but I'd be surprised if that's the case. However, I'd recommend you wait for someone with more recent Bitmap experience to make sure I'm not saying something incorrect (which wouldn't be 1st time). – Martin Marconcini Oct 22 '19 at 15:36

1 Answers1

0

Android docs:

public static Bitmap createScaledBitmap ( Bitmap src, int dstWidth, int dstHeight, boolean filter )

Creates a new bitmap, scaled from an existing bitmap, when possible. If the specified width and height are the same as the current width and height of the source bitmap, the source bitmap is returned and no new bitmap is created.

So just make sure your scaled bitmap dimens are different from source bitmap.

Vlad Davidchenko
  • 454
  • 1
  • 7
  • 24
Rishabh Dhawan
  • 519
  • 1
  • 3
  • 11