简体   繁体   中英

How to get bitmap from imageView

I need to take an image from imageView and make it as a bitmap.

String s = getIntent().getStringExtra("ImageUri");
mImageViewFilter = (ImageView) findViewById(R.id.imageViewFilter);
Glide.with(this)
          .load(s)
          .into(mImageViewFilter);
Bitmap bitmap = ((BitmapDrawable)mImageViewFilter.getDrawable()).getBitmap();

You can see that into mImageViewFilter I am loading a photo with use of its URI and Glide library. My next step is to take this photo which is in mImageViewFilter and make it as a bitmap. After the last line of code there is an exception. What am I doing wrong?

String s = getIntent().getStringExtra("ImageUri");
mImageViewFilter = (ImageView) findViewById(R.id.imageViewFilter);

To load image into ImageView use below code

Glide.with(this).load(s).into(mImageViewFilter);

So in order to get bitmap from ImageView (mImageViewFilter )

Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

OR

You can add this before the code where you are trying to get Bitmap out of the ImageView

mImageViewFilter.setDrawingCacheEnabled(true);

In order to get the Bitmap out of the ImageView using DrawingCache, you first need to enable ImageView to draw image cache.

Bitmap bitmap = mImageViewFilter.getDrawingCache();

First take it as bitmap, then take it again to apply to our ImageView :

Bitmap bitmap = Glide.with(this) //taking as bitmap
    .load(s)
    .asBitmap()
    .into(100, 100) //width and height
    .get();
Glide.with(this) //apply to imageview
      .load(s)
      .into(mImageViewFilter);

Actually you doing right thing. But the problem is Image loading is Asynchronous call.
And you called getBitmap() in right next line which will be called sequentially. And it will give you null anyway cause image is not loaded yet .

Solution if you want to do it in next direct step .You can use direct Bitmap callback.

Glide.with(this)
    .asBitmap()
    .load(path)
    .into(new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
            imageView.setImageBitmap(resource);
           // Use resource as bitmap save it for later.
        }
    });

The straightforward way to obtain a bitmap from any View including ImageView is to get the drawing cache from it.

mImageViewFilter.buildDrawingCache();
Bitmap bitmap = mImageViewFilter.getDrawingCache();

But the above method may give you a low quality image.

I think you should directly decode the bitmap from the Uri using BitmapFactory

InputStream in = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM