Answers:
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
image.getDrawable()真的可以投射到BitmapDrawable(避免IllegalCastExceptions)。例如,如果您在图像中使用图层,则此片段将略有不同:Bitmap bitmap = ((BitmapDrawable)((LayerDrawable)image.getDrawable()).getDrawable(0)).getBitmap();
ImageView从中设置了图像,这行得通URI吗?imageView.setImageUri()
这将使您Bitmap从中受益ImageView。但是,它与您设置的位图对象不同。这是一个新的。
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
===编辑===
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 bmap = Bitmap.createBitmap(mImageView.getDrawingCache());
写下面的代码
ImageView yourImageView = (ImageView) findViewById(R.id.yourImageView);
Bitmap bitmap = ((BitmapDrawable)yourImageView.getDrawable()).getBitmap();
对于那些谁正在寻找Kotlin解决方案,使Bitmap从ImageView。
var bitmap = (image.drawable as BitmapDrawable).bitmap
这段代码更好。
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();
}
Bitmap imagenAndroid = BitmapFactory.decodeResource(getResources(),R.drawable.jellybean_statue);
获取图像位图的另一种方法是:
Bitmap imagenAndroid = BitmapFactory.decodeResource(getResources(),R.drawable.jellybean_statue);
imageView.setImageBitmap(imagenAndroid);
试试这个代码:
Bitmap bitmap;
bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();