我找到了很多关于如何加载大位图和避免内存不足异常的文档。但问题是我必须从我的 MediaStore.Images.media 中获取图像,所以经典
谷歌文档中指示的 decodeFile(path,options)
对我不起作用
正如您在下面看到的,我取消了行 //Bitmap photo= Mediastore.Images
的注释,这是触发内存不足的那一行。在另一边添加
Bitmap bm=BitmapFactory.decodeFile(selectedImageToUri,options)
行返回 null
,尽管编译器可以看到 selectedImageToUri
中的两个路径(表示图片所在的内容提供者)比我设置为 8 的选项值,因为我想缩小所有图像
我的问题是如何在 bm 中插入引用用户在图库中选择的图像的位图。在行中 BitMap photo
不返回 null 并且工作得很好,但我取消了评论,因为在我更改了几个图像之后给我内存不足的异常。
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
if (flagVariable) {
if (selectedImageToUri != null) {
// BitMap photo = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), Uri.parse(selectedImageToUri));
final BitmapFactory.Options options= new BitmapFactory.Options();
options.inSampleSize=8;
Bitmap bm = BitmapFactory.decodeFile(selectedImageToUri, options);
pic = new BitmapDrawable(bm);
getActivity().getWindow().setBackgroundDrawable(pic);
} else {
getDefaultImageBackground(inflater, container);
}
hiddenList = inflater.inflate(R.layout.fragment_as_list_layout_temp, container, false);
} else {
getDefaultImageBackground(inflater, container);
}
listView = (ListView) hiddenList.findViewById(R.id.list_hidden);
最佳答案
MediaStore.getBitmap
只是一个简单的方便方法,它看起来像这样:
public static final Bitmap getBitmap(ContentResolver cr, Uri url)
throws FileNotFoundException, IOException {
InputStream input = cr.openInputStream(url);
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
您可以基于此创建自己的方法,该方法接受选项
并在BitmapFactory
上调用不同的重载:
public static final Bitmap getBitmap(ContentResolver cr,
Uri url,
BitmapFactory.Options options)
throws FileNotFoundException, IOException {
InputStream input = cr.openInputStream(url);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
input.close();
return bitmap;
}
用法:
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bm = getBitmap(getActivity().getContentResolver(),
Uri.parse(selectedImageToUri),
options);
关于android - 大位图内存不足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36912112/