鉴于
ImageView image = R.findViewById(R.id.imageView); image.setImageBitmap(someBitmap);
是否有可能检索位图?
这将从ImageView得到一个Bitmap。但是,它不是您所设置的位图对象。这是一个新的。
ImageView
Bitmap
imageView.buildDrawingCache(); Bitmap bitmap = imageView.getDrawingCache();
=== edit ===
imageView.setDrawingCacheEnabled(true); imageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); imageView.layout(0, 0, imageView.getMeasuredWidth(), imageView.getMeasuredHeight()); imageView.buildDrawingCache(true); Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache()); imageView.setDrawingCacheEnabled(false);
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
另一种获取图像位图的方法是这样做:
Bitmap imagenAndroid = BitmapFactory.decodeResource(getResources(),R.drawable.jellybean_statue); imageView.setImageBitmap(imagenAndroid);
试试下面的代码:
Bitmap bitmap; bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
这段代码更好。
public static byte[] getByteArrayFromImageView(ImageView imageView) { BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.getDrawable()); Bitmap bitmap; if(bitmapDrawable==null){ imageView.buildDrawingCache(); bitmap = imageView.getDrawingCache(); imageView.buildDrawingCache(false); }else { bitmap = bitmapDrawable .getBitmap(); } ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); return stream.toByteArray(); }
编写以下代码
ImageView yourImageView = (ImageView) findViewById(R.id.yourImageView); Bitmap bitmap = ((BitmapDrawable)yourImageView.getDrawable()).getBitmap();
对于那些正在寻找Kotlin解决方案从ImageView得到Bitmap的人。
Kotlin
var bitmap = (image.drawable as BitmapDrawable).bitmap