Câu trả lời:
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
image.getDrawable()thực sự có thể được đúc BitmapDrawable(để tránh IllegalCastExceptions). Ví dụ: nếu bạn sử dụng các lớp trong hình ảnh của mình thì đoạn trích này sẽ hơi khác một chút:Bitmap bitmap = ((BitmapDrawable)((LayerDrawable)image.getDrawable()).getDrawable(0)).getBitmap();
ImageViewđược đặt từ URI? imageView.setImageUri()
Điều này sẽ giúp bạn có được Bitmaptừ ImageView. Mặc dù vậy, nó không phải là cùng một đối tượng bitmap mà bạn đã đặt. Nó là một cái mới.
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
=== CHỈNH SỬA ===
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());
Viết mã dưới đây
ImageView yourImageView = (ImageView) findViewById(R.id.yourImageView);
Bitmap bitmap = ((BitmapDrawable)yourImageView.getDrawable()).getBitmap();
Đối với những người đang tìm kiếm Kotlingiải pháp để có được Bitmaptừ ImageView.
var bitmap = (image.drawable as BitmapDrawable).bitmap
Mã này là tốt hơn.
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);
Một cách khác để có được một bitmap của một hình ảnh là làm điều này:
Bitmap imagenAndroid = BitmapFactory.decodeResource(getResources(),R.drawable.jellybean_statue);
imageView.setImageBitmap(imagenAndroid);
thử mã này:
Bitmap bitmap;
bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();