【问题标题】:Out of memory error when calling createBitmap [duplicate]调用 createBitmap 时出现内存不足错误 [重复]
【发布时间】:2014-08-14 04:43:12
【问题描述】:

我试图解决Android Camera Intent Saving Image Landscape When Taken Portrait 的问题,但遇到了dalvikvm-heap Out of memory on a 63489040-byte allocation. 错误的问题。我查看了createBitmap() leads me into a java.lang.OutOfMemoryError,但这个问题没有任何帮助。我不知道如何解决这个问题。我尝试在位图上调用recycle(),但没有成功。

String file = getRealPathFromURI(Uri.parse(mUriString));
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, bounds);

BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(file, opts);
ExifInterface exif = new ExifInterface(file);
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
int rotationAngle = 0;

switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
    rotationAngle = 90;
case ExifInterface.ORIENTATION_ROTATE_180:
    rotationAngle = 180;
case ExifInterface.ORIENTATION_ROTATE_270:
    rotationAngle = 270;
}

Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
bm.recycle();

此代码读取 EXIF 数据并正确定位图像。

我还应该补充一点,我正在这里压缩图像:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
rotatedBitmap.recycle();
baos.close();

【问题讨论】:

    标签: java android image memory bitmap


    【解决方案1】:

    当您解码BitmapFactory.Options 中的图像时,您可以通过跳过ARGB_8888 并改用RGB_565 来减少内存。和 inDither 为 true 以保持图像质量。

    样本:

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

    【讨论】:

    • 有什么办法可以破坏图像压缩?
    • @lschessinger 你怎么能说它会破坏压缩?
    • 没关系。不相关的问题(我认为)。
    【解决方案2】:

    您可以使用opts.inSampleSize = 2 or above 来避免OOM 异常。

    【讨论】:

      猜你喜欢
      • 2011-05-05
      • 1970-01-01
      • 2015-11-26
      • 2012-12-01
      • 1970-01-01
      • 2022-01-12
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多