简体   繁体   English

如何从ImageView获取位图

[英]How to get a Bitmap from an ImageView

I wish to get a Bitmap from an ImageView loaded with Glide like such: 我希望从装有GlideImageView获取一个Bitmap ,如下所示:

Glide.with(getContext()).load(URL)
            .thumbnail(0.5f)
            .crossFade()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(my_imageView);

I have tried the following: 我尝试过以下方法:

imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();

and

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

And none of them has worked for me so far. 到目前为止,他们都没有为我工作过。

How can this be achieved? 怎么能实现这一目标?

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: 您需要在尝试从BitView中获取Bitmap的代码之前添加此项:

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. 为了使用DrawingCache将Bitmap从ImageView中取出,首先需要enable ImageView来绘制图像缓存。

then: 然后:

Bitmap bmap = imageView.getDrawingCache();

Also, calling buildDrawingCache(); 另外,调用buildDrawingCache(); is equivalent to calling buildDrawingCache(false); 相当于调用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: 我遇到的问题是位图仍然总是导致null(即使使用绘图缓存,可能是一些与Facebook ShareButton / ShareContent竞争)所以我有以下解决方案,以确保滑动完成加载图像:

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;
    }
};

presently setDrawingCacheEnabled has been deprecated , so another solution is using 目前setDrawingCacheEnabled已被弃用 ,因此另一种解决方案正在使用

ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

Or to obtain Bitmap from Uri , we can use the Glide library. 或者要从Uri获取Bitmap ,我们可以使用Glide库。

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 . 使用Glide非常适合处理bitmaps Refer the docs at Handling Bitmaps 请参阅处理位图的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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