我从服务器获取图像数据,我使用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