如何处理android中的java.lang.OutOfMemoryError错误?

时间:2013-10-31 15:26:37

标签: android bitmap

我正在我的应用中通过我的设备拍摄照片并将其保存到服务器

我正在使用三星音符2

但是我收到了这个错误

10-31 20:34:06.759: E/AndroidRuntime(12985): FATAL EXCEPTION: Thread-5431
10-31 20:34:06.759: E/AndroidRuntime(12985): java.lang.OutOfMemoryError
10-31 20:34:06.759: E/AndroidRuntime(12985):    at android.graphics.Bitmap.nativeCreate(Native Method)
10-31 20:34:06.759: E/AndroidRuntime(12985):    at android.graphics.Bitmap.createBitmap(Bitmap.java:640)
10-31 20:34:06.759: E/AndroidRuntime(12985):    at android.graphics.Bitmap.createBitmap(Bitmap.java:586)
10-31 20:34:06.759: E/AndroidRuntime(12985):    at com.winit.dropbox.MainScreen.flip(MainScreen.java:1241)
10-31 20:34:06.759: E/AndroidRuntime(12985):    at com.winit.dropbox.MainScreen$DropBoxUploader.run(MainScreen.java:1166)
10-31 20:34:06.759: E/AndroidRuntime(12985):    at java.lang.Thread.run(Thread.java:856)

代码指向此行,

        Bitmap dst = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, false);

而m是

Matrix m = new Matrix();
编辑:我现在已经在创建位图期间删除了矩阵,但现在我在调整通过Android设备拍摄的图像时遇到问题,即时使用

bmp = BitmapsUtiles.getResizedBmp(bmp, AppConstants.DEVICE_WIDTH, AppConstants.DEVICE_HEIGHT);

但是它仍然没有用,你能指出它在调整大小时我做错了吗

1 个答案:

答案 0 :(得分:0)

这就是我解码位图的方法。希望能帮助到你。 基本上我不是加载整个图片而只是加载所需大小的位图。否则我经常会出现内存不足错误。

public static Bitmap decodeSampledBitmapFromResource(String filePath,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    //this avoids memory allocation
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(filePath, options);
}


private 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;
}