trocchietto trocchietto - 10 months ago 68
Android Question

outofmemory exception for Large Bitmap

I found a lot of documentation on how to load large Bitmaps and avoid outofmemory exception. but the problem is that I have to take the image from my so the classical

indicated in the google documentation does not work to me

As you can see below I decommented the line
// Bitmap photo= Mediastore.Images
, that is the one that triggers the out of memory. on the other side adding
the line
Bitmap bm=BitmapFactory.decodeFile(selectedImageToUri,options)
, although the compiler can see both the path in
(that indicates the content provider where the pics are) than the options value, that I set to 8, because I want to subscale all the images

My question is how can I insert in bm the bitmap that is referring to the image selected by the user in the gallery. in the line
BitMap photo
does not return null and work really well, but I decommented because after I change a couple of images gives me outofmemory exception.

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();

Bitmap bm = BitmapFactory.decodeFile(selectedImageToUri, options);

pic = new BitmapDrawable(bm);


} else {
getDefaultImageBackground(inflater, container);


hiddenList = inflater.inflate(R.layout.fragment_as_list_layout_temp, container, false);

} else {
getDefaultImageBackground(inflater, container);

listView = (ListView) hiddenList.findViewById(;


MediaStore.getBitmap is just a simple convienence method, it looks like this:

public static final Bitmap getBitmap(ContentResolver cr, Uri url)
                throws FileNotFoundException, IOException {
    InputStream input = cr.openInputStream(url);
    Bitmap bitmap = BitmapFactory.decodeStream(input);
    return bitmap;

You can create your own method based on this that takes the options and calls a different overload on 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);
    return bitmap;


final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;

Bitmap bm = getBitmap(getActivity().getContentResolver(),