【问题标题】:Android - OutOfMemoryError when downsampling large camera imagesAndroid - 对大型相机图像进行下采样时出现 OutOfMemoryError
【发布时间】:2013-03-28 19:04:12
【问题描述】:

我在从相机活动捕获图像、将其保存为较小尺寸并将保存的图像上传到我的服务器时遇到间歇性问题。

如果图像文件大于特定阈值(我使用 2,000KB),我将调用以下函数对其进行下采样并保存较小的图像:

private void downsampleLargePhoto(Uri uri, int fileSizeKB)
{
    int scaleFactor = (int) (fileSizeKB / fileSizeLimit);
    log("image is " + scaleFactor + " times too large");

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    try
    {           
        options.inJustDecodeBounds = false;
        options.inSampleSize = scaleFactor;
        Bitmap scaledBitmap = BitmapFactory.decodeStream(
                    getContentResolver().openInputStream(uri), null, options);
        log("scaled bitmap has size " + scaledBitmap.getWidth() + " x " + scaledBitmap.getHeight());

        String scaledFilename = uri.getPath();
        log("save scaled image to file " + scaledFilename);
        FileOutputStream out = new FileOutputStream(scaledFilename);
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        scaledBitmap.recycle();

        File image = new java.io.File(scaledFilename);
        int newFileSize = (int) image.length()/1000;
        log("scaled image file is size " + newFileSize + " KB");
    }
    catch(FileNotFoundException f)
    {
        log("FileNotFoundException: " + f);
    }
}

但是,对于非常大的图像,我的应用程序崩溃并出现 OutOfMemoryError 就行了:

Bitmap scaledBitmap = BitmapFactory.decodeStream(
                    getContentResolver().openInputStream(uri), null, options);

此时我还能做些什么来缩小图像?

【问题讨论】:

标签: android image bitmap out-of-memory


【解决方案1】:

您实际上还没有尝试正确使用 API。您应该设置 inJustDecodeBounds = true 然后调用 decodeStream()。一旦您获得了解码图像的大小,您就可以为 inSampleSize 选择一个适当的值 - 这应该是 (a) 2 的幂,并且 (b) 与压缩图像文件的大小无关 - 然后调用 decodeStream( ) 第二次。

为了选择合适的 inSampleSize 值,我通常参考屏幕尺寸,即如果图像最大边缘是屏幕最大边缘的两倍以上,则设置 inSampleSize=2。等等等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-29
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2014-05-04
    • 2015-08-08
    相关资源
    最近更新 更多