Efficient way of creating Bitmap out of Drawable from res (BitmapFactory vs Type Casting)
Asked Answered
B

4

6

Which method is more efficient for creating Bitmap out of Drawable from resources?

Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.icon_resource);

Vs

Drawable myDrawable = getResources().getDrawable(R.drawable.icon_resource);
Bitmap myBitmap = ((BitmapDrawable) myDrawable).getBitmap();

since API 22 above method is deprecated so use following

Drawable myDrawable = ContextCompat.getDrawable(context, R.drawable.icon_resource)
Bucher answered 12/2, 2013 at 20:13 Comment(0)
A
1

You can take a look at the source code for Bitmap factory at http://source.android.com specifically the code for decodeResource.

I would reason that using BitmapFactory is preferred but in either case if you are decoding multiple bitmaps then you should call getResources() once and store the result for use as the resources argument for the functions.

Annaleeannaliese answered 12/2, 2013 at 20:20 Comment(1)
Hi Merlin, I took look at source code of “decodeResource” so far I am only able to understand it help in creating scaled bitmap according to “Option parameter” which is null in my case. I still fill typecasting is better option as it doesn’t involve any encoding/decoding. Correct me if I am wrong.Bucher
B
0
Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.icon_resource);

As per the documentation above method is best when we are constructing bitmap from inputStream

Vs

Drawable myDrawable = ContextCompat.getDrawable(context, R.drawable.icon_resource)
Bitmap myBitmap = ((BitmapDrawable) myDrawable).getBitmap();

This solution is widely used and better in performance as it simply returns the bitmap used by this drawable to render.

Bucher answered 8/8, 2017 at 19:53 Comment(0)
T
0

Both should have similar decoding performance. In fact, initial creation of the Drawable will call Drawable.createFromResourceStream() which calls BitmapFactory.decodeResourceStream().

However, Resources.getDrawable() and Context.getDrawable() use a Drawable cache, so if you are loading the same Bitmap more than once using this API it can skip decoding if the Drawable is in the cache and performance will be better.

Trader answered 8/8, 2017 at 20:25 Comment(0)
F
0

Both methods are very efficient, but might run much slower in low end devices.

You need to call decodeResource() only once per ResId, (and even possibly on a separate thread) then store the loaded resource in memory for subsequent calls, in order to prevent the infamous ANR (Application Not Responding).

Foraminifer answered 15/5, 2023 at 2:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.