[英]Convert image to bitmap and compress
I have a function convert image to array byte (to save image into database sqlite). 我有一个将图像转换为数组字节的功能(将图像保存到数据库sqlite)。 I have a problem, how to compress image and avoid out of memory error? 我有一个问题,如何压缩图像并避免出现内存不足错误? This is my code Thanks in advance. 这是我的代码,谢谢。
public byte[] ConverttoArrayByte(ImageView img)
{
try{
BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}catch (NullPointerException e){
Log.d("Tag", "Null");
e.printStackTrace();
}
return null;
}
You can try to use a small function that resizes the image: 您可以尝试使用调整图像大小的小功能:
public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
And call this function in this way Bitmap bitmap = GetAttachmentsUtils.getResizedBitmap(bitmap, maxSize);
并以这种方式调用此函数Bitmap bitmap = GetAttachmentsUtils.getResizedBitmap(bitmap, maxSize);
to get the resized bitmap. 获得调整大小的位图。
Then you can compress it using bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
然后,您可以使用bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
对其进行压缩bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
and perform the same operations you were doing previously. 并执行与之前相同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.