By ilredelweb


2010-10-07 08:43:41 8 Comments

How to get a Bitmap object from an Uri (if I succeed to store it in /data/data/MYFOLDER/myimage.png or file///data/data/MYFOLDER/myimage.png) to use it in my application?

Does anyone have an idea on how to accomplish this?

13 comments

@Ika 2019-09-19 09:53:08

It seems that MediaStore.Images.Media.getBitmap was deprecated in API 29. The recommended way is to use ImageDecoder.createSource which was added in API 28.

Here's how getting the bitmap would be done:

    val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        ImageDecoder.decodeBitmap(ImageDecoder.createSource(requireContext().contentResolver, imageUri))
    } else {
        MediaStore.Images.Media.getBitmap(requireContext().contentResolver, imageUri)
    }

@Mark Ingram 2011-01-17 20:48:15

Here's the correct way of doing it:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri imageUri = data.getData();
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}

If you need to load very large images, the following code will load it in in tiles (avoiding large memory allocations):

BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(myStream, false);  
Bitmap region = decoder.decodeRegion(new Rect(10, 10, 50, 50), null);

See the answer here

@pjv 2011-06-03 11:16:43

This code doesn't deal with bigger images though (basically anything wallpaper size). getBitmap() calls decodeStream() which fails with the OOM error from stackoverflow.com/questions/2220949/handling-large-bitmaps. Any other advice? MediaStore.Images.Thumbnails.getThumbnail() apparently does not take a contentURI.

@Mark Ingram 2011-06-03 20:32:48

@Narendra Singh 2015-07-03 06:12:04

@MarkIngram Does this work with any local image or just the camera image?

@Umair 2016-06-25 21:47:13

@MarkIngram what if we dont have access to data.getData(), I mean if I simply open some image from gallery and I all know is about its path, how can I get uri and bitmap?

@winklerrr 2017-01-24 11:31:58

@Umair you should ask a new question instead of asking in the comments of an answer. By the way: have a look here developer.android.com/reference/android/net/Uri.html

@winklerrr 2017-01-24 11:32:01

@King this works also with local images

@Cullub 2018-04-14 00:42:20

It's telling me Unhandled exception: java.io.IOException with the red squiggly lines underneath. Any idea why?

@Cullub 2018-04-14 14:32:15

Well I ended up putting a try-catch statement around it, and it got rid of the error. I wonder why it requires you to catch possible errors...

@Mohsin kazi 2019-07-29 10:07:02

It throws IOException please update this answer with try catch block

@Mark Ingram 2019-07-29 10:42:43

@Mohsinkazi, try/catch isn't relevant to the answer, and it certainly doesn't improve the readability of the code.

@Mohsin kazi 2019-07-29 10:49:37

@MarkIngram I agree that try catch block doesn't necessary but in some situation getBitmap() method throws exception. It happened with me so I suggested to add try catch block to make this code more usable.

@Mark Ingram 2019-07-29 11:39:33

@Mohsinkazi, the code isn't intended to be copy + pasted into a project without thought. It's merely providing an answer to the question.

@Mohsin kazi 2019-07-29 13:32:24

@MarkIngram but not applicable for all those, who want Bitmap from an Uri. By the way thank you for your answer it help me.

@Hasib Akter 2018-05-28 17:26:14

This is the easiest solution:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);

@Zzmilanzz Zzmadubashazz 2017-11-25 14:06:01

Full method to get image uri from mobile gallery.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                Uri filePath = data.getData();

     try { //Getting the Bitmap from Gallery
           Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
           rbitmap = getResizedBitmap(bitmap, 250);//Setting the Bitmap to ImageView
           serImage = getStringImage(rbitmap);
           imageViewUserImage.setImageBitmap(rbitmap);
      } catch (IOException e) {
           e.printStackTrace();
      }


   }
}

@Ahmed Sayed 2018-08-02 10:58:13

Uri imgUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imgUri);

@Michael Dodd 2018-08-02 11:18:33

Could you please elaborate on how this code works and how it answers the question?

@Emre AYDIN 2018-04-27 06:50:04

You can retrieve bitmap from uri like this

Bitmap bitmap = null;
try {
    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
    e.printStackTrace();
}

@Shubham Ratawa 2018-03-28 11:51:13

Bitmap imgbitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);

@Nico Haase 2018-03-28 12:11:23

This has already been answered. Is there anything new you'd like to point out?

@Faxriddin Abdullayev 2017-07-11 10:28:41

Use startActivityForResult metod like below

        startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"), PICK_IMAGE);

And you can get result like this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        return;
    }
    switch (requestCode) {
        case PICK_IMAGE:
            Uri imageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
         break;
    }
}

@Sayed Mohammad Amin Emrani 2017-06-20 15:16:15

you can do this structure:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                    Uri selectedImage = imageReturnedIntent.getData();
                    Bundle extras = imageReturnedIntent.getExtras();
                    bitmap = extras.getParcelable("data");
            }
            break;
   }

by this you can easily convert a uri to bitmap. hope help u.

@Developer_vaibhav 2018-01-03 16:07:40

This is not working in android nougat 7.1.1 version. This extras.getParcelable("data"); is returning null

@pjv 2011-06-03 14:13:47

Here's the correct way of doing it, keeping tabs on memory usage as well:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
  super.onActivityResult(requestCode, resultCode, data);
  if (resultCode == RESULT_OK)
  {
    Uri imageUri = data.getData();
    Bitmap bitmap = getThumbnail(imageUri);
  }
}

public static Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException{
  InputStream input = this.getContentResolver().openInputStream(uri);

  BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
  onlyBoundsOptions.inJustDecodeBounds = true;
  onlyBoundsOptions.inDither=true;//optional
  onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
  BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
  input.close();

  if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
    return null;
  }

  int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;

  double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0;

  BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
  bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
  bitmapOptions.inDither = true; //optional
  bitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//
  input = this.getContentResolver().openInputStream(uri);
  Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
  input.close();
  return bitmap;
}

private static int getPowerOfTwoForSampleRatio(double ratio){
  int k = Integer.highestOneBit((int)Math.floor(ratio));
  if(k==0) return 1;
  else return k;
}

The getBitmap() call from Mark Ingram's post also calls the decodeStream(), so you don't lose any functionality.

References:

@Praween k 2013-07-09 09:53:24

Thanks for this detail explanation.

@MacKinley Smith 2013-09-16 14:39:08

This really helped me, although I think it's worth mentioning that the this keyword can't be used from within a static context. I passed it into the getThumbnail method as an argument and it works like a charm.

@Dr. aNdRO 2013-10-17 04:42:47

Thanks a lot dude !

@Michal 2014-03-26 21:48:29

Why are you closing the stream after first decode?

@pjv 2014-08-07 19:59:46

@Michal Closing because you don't need it any more? I guess I was conservative here when I wrote this 3 years ago.

@Abid 2014-12-24 07:46:04

Can any one tell me what value should i give to THUMBNAILSIZE

@DominicM 2015-01-31 21:11:50

Closing and reopening the InputStream is actually necessary because the first BitmapFactory.decodeStream(...) call sets the reading position of the stream to the end, so the second call of the method wouldn't work anymore without reopening the stream!

@war_Hero 2015-03-24 10:04:53

please tell the value of THUMBNAILSIZE

@Abx 2015-06-16 10:45:04

THUMBNAILSIZE ,as the name suggests is the size of the image to be shown as a thumbnail ie. the thumbnail display size

@Fay007 2015-12-22 12:24:57

it gives me java.io.FileNotFoundException: No content provider:

@Bawa 2016-11-13 19:40:56

You just saved a life today bro <3 this community never disappoints me, :)

@winklerrr 2017-01-25 12:15:21

@war_Hero THUMBNAILSIZE should be the size of the view which is going to show the thumbnail.

@winklerrr 2017-01-25 12:20:47

It's unnecessary to calculate the ratio as a power of two by yourself because the decoder itself rounds to sample size down to the nearest power of two. Therefore the method call getPowerOfTwoForSampleRatio() can be skipped. See: developer.android.com/reference/android/graphics/…

@DjP 2013-09-13 11:24:13

try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
}
catch (Exception e) 
{
    //handle exception
}

and yes path must be in a format of like this

file:///mnt/sdcard/filename.jpg

@DjP 2013-09-13 12:21:47

thanks Itay, this is simple , if u have the path u just have to pass that path and get the Bitmap .. it is working for me , hope to u also try this..

@Nezneika 2013-10-29 09:52:58

@Dhananjay Thank you, your hint saves my day, and it works to load the thumbnail bitmap from Content Provider.

@Nezneika 2013-10-29 10:13:34

In addition, the Uri.parse() must contain URI format, just like: Uri.parse("file:///mnt/sdcard/filename.jpg"), if not we will get java.io.FileNotFoundException: No content provider.

@umassthrower 2014-02-04 23:17:33

Some editorialization would be nice, but this is a good concise answer to the OPs question that works in most cases. This is a nice answer to have on the page for the sake of distilling out the piece of these other answers that directly answer the OPs questions.

@AndroidNewBee 2016-09-27 06:28:38

@Crazy what is c in c.getContentResolver()

@DjP 2016-09-27 08:00:12

@AndroidNewBee c is Context object.

@Android Man 2017-01-09 14:57:50

not working in my case getting exception Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference

@DeltaCap019 2015-08-27 15:12:29

 private void uriToBitmap(Uri selectedFileUri) {
        try {
            ParcelFileDescriptor parcelFileDescriptor =
                    getContentResolver().openFileDescriptor(selectedFileUri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);


            parcelFileDescriptor.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

@Jigar Patel 2017-01-18 10:12:26

it's works on all sdk.. Thanks. it's alternative way of Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver‌​(), uri);

@Noaman Akram 2019-08-03 23:15:50

the most genuine answer all SDK satisfied

@Vidar Vestnes 2010-10-07 08:46:10

. . IMPORTANT: See answer from @Mark Ingram below and @pjv for at better solution. . .

You could try this:

public Bitmap loadBitmap(String url)
{
    Bitmap bm = null;
    InputStream is = null;
    BufferedInputStream bis = null;
    try 
    {
        URLConnection conn = new URL(url).openConnection();
        conn.connect();
        is = conn.getInputStream();
        bis = new BufferedInputStream(is, 8192);
        bm = BitmapFactory.decodeStream(bis);
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
    finally {
        if (bis != null) 
        {
            try 
            {
                bis.close();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
        if (is != null) 
        {
            try 
            {
                is.close();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }
    return bm;
}

But remember, this method should only be called from within a thread (not GUI -thread). I a AsyncTask.

@ilredelweb 2010-10-07 08:52:03

thanx but am talking a about an URI not an URL

@Vidar Vestnes 2010-10-07 15:05:20

What about converting the URI to an url, e.g by using yourUri.toURL() ?

@dharam 2013-06-27 10:20:30

@VidarVestnes buddy , how can file path converted on Url ?

@Temporary 2014-02-27 23:45:08

I don't understand how this is the selected answer

@Vidar Vestnes 2014-02-28 11:20:58

I agree, this answer should not be accepted as the best. Maybe it was choosen because It was the first answer. Its a old post. Anyway, se answers below for better solutions.

@winklerrr 2017-01-24 11:23:31

@VidarVestnes just delete your answer

@Pulathisi Bandara 2017-10-28 16:55:05

Nice answer where you have to understand the logic (y)

@Saad Bilal 2019-01-16 06:51:51

This is really bad approach to deal with it.

@Chisko 2019-01-31 20:12:33

delete this for your dignity's sake

@Daniel Beltrami 2019-04-04 19:26:13

URI is almost URL, is like a doctor when give a wrong medicine because a wrong caracter and kill someone lol

@Dexter 2019-04-14 14:50:23

Here question is about uri not URL

Related Questions

Sponsored Content

51 Answered Questions

[SOLVED] Stop EditText from gaining focus at Activity startup

43 Answered Questions

25 Answered Questions

[SOLVED] Get filename and path from URI from mediastore

19 Answered Questions

[SOLVED] Save bitmap to location

  • 2009-03-16 03:26:06
  • Chrispix
  • 458871 View
  • 449 Score
  • 19 Answer
  • Tags:   android bitmap save

17 Answered Questions

[SOLVED] How to convert a Drawable to a Bitmap?

7 Answered Questions

[SOLVED] Convert file path to a file URI?

  • 2009-10-09 22:44:24
  • Tinister
  • 179331 View
  • 190 Score
  • 7 Answer
  • Tags:   c# .net path uri

34 Answered Questions

[SOLVED] Android Studio: Add jar as library?

31 Answered Questions

[SOLVED] What is the difference between a URI, a URL and a URN?

  • 2008-10-06 21:26:58
  • Sean McMains
  • 1093042 View
  • 4178 Score
  • 31 Answer
  • Tags:   http url uri urn rfc3986

30 Answered Questions

[SOLVED] How do I obtain crash-data from my Android application?

Sponsored Content