TimmyMa
TimmyMa

Reputation: 175

BitmapFactory.decodeFile returns null

I'm going to compress image with Bitmap.compress() method.

But when I get Bitmap using bitmap = BitmapFactory.decodeFile() I get a null object, and the method didn't thow any exception.

Here's my code

public static File compressImage(String imagePath) throws IOException {

    // Get bitmap
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

    // Get bitmap output stream
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);

......

When the code runs at the last line I get a NullPointerException :

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference

Then I run my code in debug mode, it turns out I got a null object from BitmapFactory.decodeFile method.

The parameter imagePath is

/storage/emulated/0/DCIM/Camera/IMG_20160610_195633.jpg

which seems ok.

This piece of code works well in another activity, but when i copy it to a async thread which I attempt to compress and upload images, it crashed. Is there any possibilities that this is because the async thread thing? Or something else I didn't notice?

Upvotes: 4

Views: 1643

Answers (2)

Clark W
Clark W

Reputation: 73

This answer applies if you are using your phone connected via USB to debug your code. My phone indicates Android version 6.0.1.

I read all of the posts about setting my "Uses-permission" fields and my code still didn't work. I found, however, that I needed to go into my device under "settings->device->applications->application manager" and then click on the application I was debugging and navigate to "Permissions" and manually enable the requested permissions.

The following permissions must be in your AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Upvotes: 0

earthw0rmjim
earthw0rmjim

Reputation: 19417

Remove the following from your code:

options.inJustDecodeBounds = true;

From the documentation of inJustDecodeBounds:

If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

inJustDecodeBounds is useful to load large Bitmaps efficiently, since you can read their dimensions without having to allocate the memory for them, although it has no purpose in your code.

Upvotes: 4

Related Questions