我需要让用户从他们的图库中打开一个特定的相册,并让他们对图像做一些事情。
为了从相册中检索图像,我使用:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri).
一切工作正常,除了如果相册包含许多图片,它最终会拖拽一个OutOfMemoryException.
现在,我知道如何基于Android guidelines缓解这个问题,但问题是我已经用getBitmap()检索了原始的位图
那么,有没有可能检索字节数组格式或输入流格式的图像,并在将其分配到内存之前按比例缩小,以避免内存泄漏?( Android指南的建议也是如此)
发布于 2012-07-27 19:46:34
因此,有一个图像Uri在我手中,我想要检索它的InputStream,并在将其分配到内存之前缩小图像,以避免OutOfMemoryException
解决方案:
要从Uri检索InputStream,您必须调用以下代码:
InputStream stream = getContentResolver().openInputStream(uri);然后按照安卓在loading bitmaps efficiently上的建议,你只需要调用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;
}发布于 2012-07-27 18:59:44
您已经确定了一个非常好的解决方案。如果您想跳过通过MediaStore将镜像拉入Bitmap的步骤,请尝试使用ImageView.setImageUri()。
https://stackoverflow.com/questions/11686361
复制相似问题