从Android L中的ImageView获取位图

Utk*_*tav 32 java android bitmap imageview android-layout

我想BitmapImageView.我使用了以下代码,但getDrawable()返回null.如何让整个BitmapImageView.

Bitmap bitmap;
if (mImageViewer.getDrawable() instanceof BitmapDrawable) {
    bitmap = ((BitmapDrawable) mImageViewer.getDrawable()).getBitmap();
} else {
    Drawable d = mImageViewer.getDrawable();
    bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    d.draw(canvas);
}
storeImage(bitmap,"final.jpeg");
Run Code Online (Sandbox Code Playgroud)

Pan*_*ora 52

试试这个:

imageView.invalidate();
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Run Code Online (Sandbox Code Playgroud)

  • 你能解释一下你为什么先失效吗?有这么好的理由吗? (8认同)
  • @Tom如果你正在使用Glide,那么试试这个 GlideBitmapDrawable 可绘制 = (GlideBitmapDrawable) image.getDrawable(); (2认同)

dro*_*dev 24

如果您只想从ImageView获取Bitmap,以下代码可能适合您: -

Bitmap bm=((BitmapDrawable)imageView.getDrawable()).getBitmap();

尝试将图像放在所有可绘制的质量文件夹中(drawable-hdpi/drawable-ldpi等)

可能是您使用的模拟器或设备具有不同的密度,并试图从另一个文件夹中提取图像.

如果您在.png,.jpg或.gif以外的图像中使用扩展名,则可能无法识别其他扩展类型.http://developer.android.com/guide/topics/resources/drawable-resource.html


ToY*_*nos 18

根据这个答案,就这样做:

imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
Run Code Online (Sandbox Code Playgroud)

  • 这不能完美地工作,通常给Canvas:尝试使用回收的位图 (2认同)

Gha*_*yas 13

对于科特林:

只需编写此代码即可从 ImageView 获取位图

imageview.invalidate()
val drawable = imageview.drawable
val bitmap = drawable.toBitmap()
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您尝试从Glide加载的图像中获取位图,那么这将对您有所帮助

 Drawable dr = ((ImageView) imView).getDrawable();
        Bitmap bmp =  ((GlideBitmapDrawable)dr.getCurrent()).getBitmap();
Run Code Online (Sandbox Code Playgroud)