Efficient way to create Bitmap from Drawable from res (BitmapFactory vs Type Casting)
Which method is more efficient for creating a Bitmap from 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 method above is deprecated, so use
Drawable myDrawable = ContextCompat.getDrawable(context, R.drawable.icon_resource)
source to share
You can see the source code for the Bitmap factory at http://source.android.com specifically for the decodeResource.
I would suggest using BitmapFactory is preferred, but anyway, if you are decoding multiple bitmaps, you should call getResources () right away and store the result to be used as a resource argument for the functions.
source to share
Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon_resource);
According to the above documentation, the method is best when we create a bitmap from an inputStream
Vs
Drawable myDrawable = ContextCompat.getDrawable(context, R.drawable.icon_resource)
Bitmap myBitmap = ((BitmapDrawable) myDrawable).getBitmap();
This solution is widely used and is better in performance because it simply returns the bitmap used by this rendering feature.
source to share
Both should have similar decoding performance. In fact, the initial creation of Drawable will invoke Drawable.createFromResourceStream()
, which will invoke BitmapFactory.decodeResourceStream()
.
However, Resources.getDrawable()
and Context.getDrawable()
use Drawable cache , so if you load the same Bitmap more than once using this API, it may skip decoding if Drawable is in the cache and performance will be better.
source to share