如何从 Uri 加载采样图像?

How to load sampled image from Uri?

我需要加载分辨率较低的图像。我该怎么做?

我厌倦了下一个代码:

public Bitmap decodeSampledBitmapFromUri(@NonNull Uri Uri, int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    try {

        InputStream is = getContentResolver().openInputStream(Uri);

        BitmapFactory.decodeStream(is, null, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);   // I can read width and height from options

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeStream(is, null, options);
    } catch (Exception ignored)
    {

    }
    return null;
}

而且我什至可以看到加载图像的宽度和高度。但是 BitmapFactory.decodeStream returns null 当我把 inJustDecodeBounds 变成 false 的时候。怎么了?

用户从图库中选择的图片。已授予所有权限。

您的 InputStream 已被第一个 decodeStream() 关闭。打开一个新的 InputStream 用于第二个 decodeStream().