【问题标题】:How to Avoid inconsistent OutOfMemory Exceptions with BitmapFactory.decodeByteArray?如何使用 BitmapFactory.decodeByteArray 避免不一致的 OutOfMemory 异常?
【发布时间】:2014-12-05 04:01:25
【问题描述】:

我的 android 应用程序有以下代码:

private PictureCallback pictureTakenCallback = new PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        Bitmap bmp = null;
        Bitmap scaledBitmap = null;
        ByteArrayOutputStream baos = null;

        showLoading(true);//UI crap

        try
        {
            bmp = BitmapFactory.decodeByteArray(data, 0, data.length); //OOM Exception Thrown Here

            //if the bitmap is smaller than 1600 wide, scale it up while preserving aspect ratio
            if(bmp.getWidth() < 1600) {
                int originalHeight = bmp.getHeight();
                int originalWidth = bmp.getWidth();

                scaledBitmap = Bitmap.createScaledBitmap(bmp, 1600,
                        originalHeight*1600/originalWidth, true);

                bmp = scaledBitmap;
                scaledBitmap = null;
            }

            baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 30, baos); // 30% compression
            image = baos.toByteArray();

            submitImage();
        }
        catch (java.lang.OutOfMemoryError e) {
            e.printStackTrace();
            showLoading(false);
        }
        catch (Exception e) {
            e.printStackTrace();
            showLoading(false);
        }
        finally
        {
            bmp = null;

            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            baos = null;
        }
    }
};

有时我让用户抱怨他们的手机出现内存不足异常。我的设备从来没有遇到过这个问题,这可能与他们的手机内存不足有关吗?

有人可以看看这段代码并给我一些提示,告诉我如何提高它的效率吗? 谢谢!

【问题讨论】:

标签: java android bitmapfactory


【解决方案1】:

总是尝试像这样在 Manifest 中 android:largeHeap="true"

<application 
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        >

【讨论】:

    【解决方案2】:

    您可以将缩小版本加载到内存中

    你需要查看Loading Large Bitmaps Efficiently开发者网站

    【讨论】:

      猜你喜欢
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      相关资源
      最近更新 更多