【问题标题】:Avoid OutOfMemoryError for Bitmap.createScaledBitmap in Android避免 Android 中 Bitmap.createScaledBitmap 的 OutOfMemoryError
【发布时间】:2014-06-19 03:36:03
【问题描述】:

我正在使用以下代码来放大图像。

bmp=new BitmapFactory().decodeFile(util.getPathFromUri(tempFile));
Bitmap scaledBitmap=Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true); //Line 2
ByteArrayOutputStream bos=new ByteArrayOutputStream();
scaledBitmap.compress(CompressFormat.JPEG, 100, bos);
bmp.recycle();
bmp=null;
OutputStream out;
out = new FileOutputStream(util.getTempFileName());
bos.writeTo(out);
bos.flush();

但有时 OutOfMemoryError 发生在第 2 行并且应用程序崩溃,我尝试将此代码包含在 try-catch 中,但我的应用程序仍然崩溃,因为 try-catch 仅捕获异常,createScaledBitmap() 函数也仅抛出 IllegalArgumentException。 因为,我不想显示图像,因此我不需要缩小它(正如我在 SOF 的其他问题中看到的那样)。 那么,如果我使用它(newWidth,newHeight),我如何预先检测到 OutOfMemoryError 会发生。有没有办法计算(newWidth, newHeight)的Bitmap在内存中所需的字节数和可以分配给bitmap的最大可用内存?

请帮忙!

【问题讨论】:

    标签: android bitmap out-of-memory


    【解决方案1】:
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Config.RGB_565;
    options.inPurgeable = true;
    options.inSampleSize = 1;
    options.inScaled = false;
    options.inDensity = DisplayMetrics.DENSITY_DEFAULT;
    options.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
    options.inScreenDensity = DisplayMetrics.DENSITY_DEFAULT;
    new BitmapFactory().decodeFile(util.getPathFromUri(tempFile),options);
    

    【讨论】:

    • 目前解码功能正常。我在 createScaledBitmap() 函数中遇到错误。如何避免?
    【解决方案2】:

    为避免 java.lang.OutOfMemory 异常,请在解码之前检查位图的尺寸,除非您绝对相信来源会为您提供可预测大小的图像数据,这些数据可以轻松放入可用内存中。更多详情见this

    【讨论】:

      【解决方案3】:

      试试这个方法来调整你的位图大小:

      Bitmap bitmpResizeResult = ThumbnailUtils.extractThumbnail(bitmapWantToResize, width, height);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-11
        • 2017-03-20
        • 2013-06-05
        • 1970-01-01
        • 1970-01-01
        • 2011-07-14
        • 2011-09-18
        • 1970-01-01
        相关资源
        最近更新 更多