Android-避免从Gallery中提取图像的内存泄漏
我需要让用户从他们的图库中打开一个特定的相册,并让他们对图像进行处理 为了从相册中检索图像,我使用:Android-避免从Gallery中提取图像的内存泄漏,android,android-layout,android-intent,android-emulator,android-widget,Android,Android Layout,Android Intent,Android Emulator,Android Widget,我需要让用户从他们的图库中打开一个特定的相册,并让他们对图像进行处理 为了从相册中检索图像,我使用: Bitmap-Bitmap=MediaStore.Images.Media.getBitmap(contentResolver,uri)。 一切正常,但如果相册包含许多图片,它最终会抛出一个OutOfMemoryException. 现在,我知道如何根据来缓解此问题,但问题是我已经在使用getBitmap() 那么,是否有可能检索字节数组格式或输入流格式的图像,并在将其分配到内存之前将其缩小,以
Bitmap-Bitmap=MediaStore.Images.Media.getBitmap(contentResolver,uri)。
一切正常,但如果相册包含许多图片,它最终会抛出一个OutOfMemoryException.
现在,我知道如何根据来缓解此问题,但问题是我已经在使用
getBitmap()
那么,是否有可能检索字节数组格式或输入流格式的图像,并在将其分配到内存之前将其缩小,以避免内存泄漏?(与Android指南的建议相同)您已经找到了一个非常好的解决方案。如果您想跳过通过
MediaStore
将图像拉入位图的步骤,请尝试使用。因此,有一个图像Uri
在我手中,我想检索它的输入流
并在内存中分配它之前缩小图像的比例,以避免OutOfMemoryException
解决方案:
要从Uri检索InputStream,必须调用:
InputStream stream = getContentResolver().openInputStream(uri);
然后,按照上的Android建议,只需调用BitmapFactory.decodeStream()
,并将BitmapFactory.Options
作为参数传递
完整源代码:
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);
助手方法:
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;
}
嗨,谢谢你的评论。尝试在缩放之前将Uri传递给ImageView也会导致OutOfMemoryException,因为图像太大。但是你为我打开了一个新的选择,基于这个图像Uri,现在我可以检索输入流并缩小图像的比例。我很快就会发布解决方案。