java - Android - 在加载到 ImageView 之前调整图像大小以避免 OOM 问题

标签 java android

从图库/照片中选择后如何减小 ImageView 上的图像尺寸?否则,选择的大图像会导致 OOM 问题。

选择 Intent

SelectImageGallery1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Image1 From Gallery"), 1);
    }
}

设置为 ImageView:

{
    Uri uri = I.getData();
    try {
        bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
        imageView1.setImageBitmap(bitmap1);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

最佳答案

查看文档的高效加载大位图部分,特别是将缩小版本加载到内存 ( https://developer.android.com/topic/performance/graphics/load-bitmap#load-bitmap )

通过设置inSampleSize,您可以在加载之前控制Bitmap 的大小。

来自文档:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

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

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, 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) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

文档使用资源作为示例,但您应该能够通过获取 InputStream 来使用 ContentResolver 并使用 BitmapFactory.decodeStream(...)

ContentResolver cr = getApplicationContext().getContentResolver();
InputStream is = cr.openInputStream(uri);

关于java - Android - 在加载到 ImageView 之前调整图像大小以避免 OOM 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59693428/

相关文章:

java - 在 Android 中创建附加文件对话框

java - `AnnotationConfigNonEmbeddedWebApplicationContext` 还没有刷新

Android - 如何获取最近捕获的图像的图像路径?

android - Android 上的 MT4 API

android - 从最近的应用程序关闭应用程序时服务停止

java - 读取大文件的最有效方法

java - Junit 在没有 ant/maven 的情况下创建报告

java - 加载大文件时tomcat重启超时

android - 断言 Mockito 模拟对象被设置为 null

android - AlarmManager 只能在不久的将来工作