Sprawl Sprawl - 7 months ago 105
Java Question

Android : FileNotFoundException when trying to get an image from Uri

I am trying to get an image's width and height in order to rezize it in case it is too big before showing it. My method receive an uri of the image but I always get a FileNotFoundException when trying to decode it using BitmapFactory.

Here is a sample of my code :

Uri myUri;

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(new File(myUri.getPath()).getAbsolutePath(), options);

int imageHeight = options.outHeight;
int imageWidth = options.outWidth;


Decode File returns throws a FileNotFoundException here. However, I can still show the image using the uri without using a bitmap factory using this :

Uri myUri;

Bitmap myBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), myUri);


The problem with this code is that the returned bitmap might cause an OutofMemoryError when using big images.

When I debug my Uri, I get this :


content://com.android.providers.media.documents/document/image%3A20472


UPDATE || Here is the working code

Uri myUri;

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;

// This is the part that changed
InputStream inputStream = context.getApplicationContext().getContentResolver().openInputStream(myUri);
BitmapFactory.decodeStream(inputStream,new Rect(),options);

int imageHeight = options.outHeight;
int imageWidth = options.outWidth;


All of this of course surrounded by try/catch.

Answer

Use decodeStream instead of decodeFile.

Open the stream with getContentResolver().openInputStream(myUri).

Comments