我从服务器获取图像数据,然后使用Base64.decode将其转换为byte []。我的代码适用于小图像尺寸,但对于大小为9.2MB的特定图像,它会崩溃。我已经阅读了各种帖子中的下采样,但在我可以进入代码的采样部分之前,我在读取以下代码行中的字节时遇到内存不足异常。 byte [] data = Base64.decode(attchData [i] .getBytes(),0);
请帮帮我。
答案 0 :(得分:0)
您可以简单地使用它并获得更好的解决方案:
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; }
答案 1 :(得分:0)
使用此方法,可能适合您
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;
}
答案 2 :(得分:0)
在Base64InputStream中换行您正在读取的输入流(从服务器读取数据时)。这应该减少base64解码阶段所需的内存量。
但是你应该检查你是否真的必须向客户发送那个大小的图像。也许图像可以在服务器端缩放?