我從服務器獲取圖像數據,我使用Base64.decode將其轉換爲byte []。我的代碼適用於小圖像尺寸,但對於9.2MB大小的特定圖像,它會崩潰。我已閱讀了各種帖子中的下采樣,但是在我可以訪問代碼的採樣部分之前,我在讀取以下代碼行中的字節時發現內存不足異常。 byte [] data = Base64.decode(attchData [i] .getBytes(),0);內存不足,而解碼圖像使用Base64解碼
請幫我一把。
我從服務器獲取圖像數據,我使用Base64.decode將其轉換爲byte []。我的代碼適用於小圖像尺寸,但對於9.2MB大小的特定圖像,它會崩潰。我已閱讀了各種帖子中的下采樣,但是在我可以訪問代碼的採樣部分之前,我在讀取以下代碼行中的字節時發現內存不足異常。 byte [] data = Base64.decode(attchData [i] .getBytes(),0);內存不足,而解碼圖像使用Base64解碼
請幫我一把。
您可以簡單地使用這一點,並得到更好的解決辦法:
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth)/width;
float scaleHeight = ((float) newHeight)/height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap; }
使用此methood,可能對您
decodeSampledBitmapFromPath(src, reqWidth, reqHeight);
使用工作這個實現
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height/(float) reqHeight);
} else {
inSampleSize = Math.round((float) width/(float) reqWidth);
}
}
return inSampleSize;
}
public Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
裹輸入流您正在從Base64InputStream中讀取數據(從服務器讀取數據時)。這應該會減少base64解碼階段所需的內存量。
但是你應該檢查你是否真的必須發送這種大小的圖像給客戶端。也許圖像可以在服務器端進行縮放?
爲什麼圖像base64編碼在第一位?這真的有必要嗎? – devconsole
你將大圖像轉換成小圖像,以避免你的問題 – KOTIOS