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?


@Fawzi Nofal 2020-02-05 12:16:27

  InputStream imageStream = null;
    try {
        imageStream = getContext().getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

@Narayan 2020-02-05 12:39:06

The answer should be informative.

@yaugenka 2020-01-06 19:58:12

Inset of getBitmap which is depricated now I use the following approach in Kotlin

    data?.data?.let {
        val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(it))

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

This is the easiest solution:

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

@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 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

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

It's telling me Unhandled exception: 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.

@sham.y 2019-10-14 09:16:55

bitmap object is becoming empty. what i am doing wrong?

@Borzh 2019-11-23 23:26:39

As this link states, you get an image thumbnail, which is about 400x100 on modern devices.

@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);
      } catch (IOException e) {


@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) {

@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:

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

@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");

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;
  BitmapFactory.decodeStream(input, null, onlyBoundsOptions);

  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
  input = this.getContentResolver().openInputStream(uri);
  Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
  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.


@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.

@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 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:…

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

    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


@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 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.

@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' 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);

        } catch (IOException e) {

@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;
        URLConnection conn = new URL(url).openConnection();
        is = conn.getInputStream();
        bis = new BufferedInputStream(is, 8192);
        bm = BitmapFactory.decodeStream(bis);
    catch (Exception e) 
    finally {
        if (bis != null) 
            catch (IOException e) 
        if (is != null) 
            catch (IOException e) 
    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 ?

@Nick Cardoso 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

104 Answered Questions

[SOLVED] Close/hide android soft keyboard

26 Answered Questions

[SOLVED] Get filename and path from URI from mediastore

52 Answered Questions

31 Answered Questions

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

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

18 Answered Questions

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

43 Answered Questions

18 Answered Questions

[SOLVED] Save bitmap to location

  • 2009-03-16 03:26:06
  • Chrispix
  • 476018 View
  • 462 Score
  • 18 Answer
  • Tags:   android bitmap save

34 Answered Questions

[SOLVED] Android Studio: Add jar as library?

30 Answered Questions

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

Sponsored Content