How to get a Bitmap from an ImageView
presently setDrawingCacheEnabled
has been deprecated, so another solution is using
ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
Or to obtain Bitmap
from Uri
, we can use the Glide library.
Bitmap bitmap = Glide.with(this) //taking as bitmap
.load(uri //Uri)
.asBitmap()
.into(100, 100) //width and height
.get();
Using Glide is quite good for handling bitmaps
. Refer the docs at Handling Bitmaps
Oh, this is a simple error. You need to add this before the code where you are trying to get Bitmap out of the ImageView:
imageView.setDrawingCacheEnabled(true);
In order to get the Bitmap
out of the ImageView using DrawingCache, you first need to enable
ImageView to draw image cache.
then:
Bitmap bmap = imageView.getDrawingCache();
Also, calling buildDrawingCache();
is equivalent to calling buildDrawingCache(false);
I had the problem that the bitmap still always resulted in null (even though using the drawing cache, probably some race with the Facebook ShareButton/ShareContent) so I had the following solution to make sure that glide was done loading the image:
Add a listener to glide
Glide.with(this)
.load(url)
.listener(listener)
.into(imageView);
The Listener
private RequestListener listener = new RequestListener() {
...
@Override
public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
Bitmap bitmap = ((BitmapDrawable) resource).getBitmap();
return false;
}
};