[英]Convert image to bitmap and compress
我有一個將圖像轉換為數組字節的功能(將圖像保存到數據庫sqlite)。 我有一個問題,如何壓縮圖像並避免出現內存不足錯誤? 這是我的代碼,謝謝。
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;
}
您可以嘗試使用調整圖像大小的小功能:
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);
}
並以這種方式調用此函數Bitmap bitmap = GetAttachmentsUtils.getResizedBitmap(bitmap, maxSize);
獲得調整大小的位圖。
然后,您可以使用bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
對其進行壓縮bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
並執行與之前相同的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.