BitmapFactory.decodeFile内存不足,图像为2400x2400

时间:2013-10-30 09:39:55

标签: android bitmap

我需要将文件从文件发送到服务器。服务器以2400x2400的分辨率请求图像。

我要做的是:

1)使用正确的inSampleSize使用BitmapFactory.decodeFile获取位图。

2)以JPEG格式压缩图像质量为40%

3)在base64中对图像进行编码

4)发送到服务器

我无法实现第一步,它会抛出一个内存不足异常。我确信inSampleSize是正确的,但我想即使使用inSampleSize,Bitmap也很大(在DDMS中大约30 MB)。

任何想法怎么做?我可以在不创建位图对象的情况下执行这些步骤吗?我的意思是在文件系统而不是RAM内存上进行。

这是当前的代码:

// The following function calculate the correct inSampleSize
Bitmap image = Util.decodeSampledBitmapFromFile(imagePath, width,height);   
// compressing the image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 40, baos);
// encode image
String encodedImage = Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));


public static 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) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromFile(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;
    return BitmapFactory.decodeFile(path,options);
}

3 个答案:

答案 0 :(得分:50)

你可以跳过ARGB_8888,然后使用RGB_565,然后抖动然后图像以保持良好的质量

 BitmapFactory.Options options = new BitmapFactory.Options();
 options.inJustDecodeBounds = false;
 options.inPreferredConfig = Config.RGB_565;
 options.inDither = true;

答案 1 :(得分:1)

您必须使用BitmapFactory.Options并将inJustDecodeBounds设置为true。这样,您可以加载有关位图的信息并计算下采样值(例如inSampleSize

答案 2 :(得分:1)

请勿将图像作为位图加载,将其转换为数组,然后发送。

代替:

以JPG格式将其作为文件读取。使用文件字节数组对其进行编码,然后跨文件发送文件。

将其加载到位图会不必要地导致巨大的内存问题。以位图格式重复显示的图像将占用大约20倍或更多的内存。

在服务器端,您还需要将其视为文件。而不是位图。

以下是将文件加载到byte []:Elegant way to read file into byte[] array in Java

的链接
相关问题