简体   繁体   中英

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.

After playing around with this for a while, I think the issue is probably that the image file really isn't there.

If you are attempting to access a local file on your computer, that file won't be in the Android sandbox where the app is actually running. You'll need to add it to the app as a resource, then access it as a resource instead of a file.

If you are attempting to access a web image, you need to download it first. The AbsolutePath of a web image ' http://example.com/example.jpg ' would be '/example.jpg', which won't do you much good when you try to open it.

Use decodeStream instead of decodeFile .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM