TimmyMa TimmyMa - 1 year ago 1691
Android Question

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
method. The parameter imagePath = "/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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download