首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android -避免从Gallery提取的图像的内存泄漏

Android -避免从Gallery提取的图像的内存泄漏
EN

Stack Overflow用户
提问于 2012-07-27 18:52:42
回答 2查看 899关注 0票数 1

我需要让用户从他们的图库中打开一个特定的相册,并让他们对图像做一些事情。

为了从相册中检索图像,我使用:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri).

一切工作正常,除了如果相册包含许多图片,它最终会拖拽一个OutOfMemoryException.

现在,我知道如何基于Android guidelines缓解这个问题,但问题是我已经用getBitmap()检索了原始的位图

那么,有没有可能检索字节数组格式或输入流格式的图像,并在将其分配到内存之前按比例缩小,以避免内存泄漏?( Android指南的建议也是如此)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-27 19:46:34

因此,有一个图像Uri在我手中,我想要检索它的InputStream,并在将其分配到内存之前缩小图像,以避免OutOfMemoryException

解决方案:

要从Uri检索InputStream,您必须调用以下代码:

代码语言:javascript
复制
InputStream stream = getContentResolver().openInputStream(uri);

然后按照安卓在loading bitmaps efficiently上的建议,你只需要调用BitmapFactory.decodeStream(),并将BitmapFactory.Options作为参数传递即可。

完整源代码:

代码语言:javascript
复制
imageView = (ImageView) findViewById(R.id.imageView);

Uri uri = Uri.parse("android.resource://com.testcontentproviders/drawable/"+R.drawable.test_image_large);
Bitmap bitmap=null;
    try {
        InputStream stream = getContentResolver().openInputStream(uri);
        bitmap=decodeSampledBitmapFromStream(stream, 150, 100);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

imageView.setImageBitmap(bitmap);

帮助器方法:

代码语言:javascript
复制
public static Bitmap decodeSampledBitmapFromStream(InputStream stream,
            int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(stream, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeStream(stream, null, options);
}

public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }
    return inSampleSize;
}
票数 0
EN

Stack Overflow用户

发布于 2012-07-27 18:59:44

您已经确定了一个非常好的解决方案。如果您想跳过通过MediaStore将镜像拉入Bitmap的步骤,请尝试使用ImageView.setImageUri()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11686361

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档