簡體   English   中英

如何避免與BitmapFactory.decodeByteArray不一致的OutOfMemory異常?

[英]How to Avoid inconsistent OutOfMemory Exceptions with BitmapFactory.decodeByteArray?

我的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;
        }
    }
};

有時,我會引起用戶抱怨內存不足異常被扔到手機上。 我的設備從未遇到此問題,這可能與手機的內存不足有關嗎?

有人可以看一下這段代碼,並給我一些提高效率的提示嗎? 謝謝!

總是嘗試在清單這樣的android:largeHeap =“ true”

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

您可以將縮小版本加載到內存中

您需要查看有效加載大型位圖的開發人員站點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM