从图库/照片中选择后如何减小 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/