从ImageView获取位图的方法

12

我希望从使用 Glide 加载的 ImageView 中获取一个 Bitmap,类似于以下方式:

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

我已经尝试了以下方法:

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

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

到目前为止,这些方法都没有对我起作用。

如何才能实现这一点?


1
我不熟悉 Glide,但最好的解决方案是从 Glide 中获取位图。如果无法实现该方法,则创建一个适当大小的 Bitmap,将其包装在 Canvas 中,并要求您的 ImageViewCanvas 上进行 draw() 操作。Bitmap 将包含结果。 - CommonsWare
4个回答

8
哦,这是一个简单的错误。在你试图从ImageView获取Bitmap的代码之前,你需要添加以下内容:
imageView.setDrawingCacheEnabled(true);

为了使用DrawingCache从ImageView中获取Bitmap,您需要先启用ImageView以绘制图像缓存。
然后:
Bitmap bmap = imageView.getDrawingCache();

此外,调用 buildDrawingCache(); 相当于调用 buildDrawingCache(false);

这很有帮助,但是当我在ImageView中加载并显示新图片时,它会显示保存的第一个位图。这是由缓存引起的吗? - user5448913
1
为什么您不在设置另一张图片之前尝试使用imageView.destroyDrawingCache()呢? - Nilesh Singh
很高兴听到这个消息。 :) - Nilesh Singh

4

事情已经发生变化,这里的答案需要更新。所以这是我的kotlin解决方案。这是简化的版本,没有综合和视图绑定(呵呵)。

    val imageView : ImageView = findViewById(R.id.my_imageview)
    val bitmap : Bitmap = imageView.drawable.toBitmap()

在进行此操作之前,请确保 ImageView 已经有足够的时间来绘制。在片段中的 onViewCreated() 或点击事件之后是一个好的时机来执行此操作。开销不应该太大。


3

我遇到了一个问题,即使使用绘图缓存,位图仍然总是为null(可能与Facebook ShareButton / ShareContent竞争),因此我有以下解决方案来确保glide已经加载完图像:

给glide添加监听器

Glide.with(this)
        .load(url)
        .listener(listener)
        .into(imageView);

监听器

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

4
如果你使用Glide的.asBitmap()方法,就可以轻松避免在监听器中进行类型转换。 - Khalid ElSayed

2

目前,setDrawingCacheEnabled已被废弃,因此另一种解决方案是使用

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

要从Uri中获取Bitmap,我们可以使用Glide库。

Bitmap bitmap = Glide.with(this) //taking as bitmap
                     .load(uri //Uri)
                     .asBitmap()
                     .into(100, 100) //width and height
                     .get();

使用Glide来处理位图非常不错。请参考处理位图文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接