Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

Smitha picture Smitha · Jan 3, 2012 · Viewed 181.7k times · Source

How can I read an image file into bitmap from sdcard?

 _path = Environment.getExternalStorageDirectory().getAbsolutePath();  

System.out.println("pathhhhhhhhhhhhhhhhhhhh1111111112222222 " + _path);  
_path= _path + "/" + "flower2.jpg";  
System.out.println("pathhhhhhhhhhhhhhhhhhhh111111111 " + _path);  
Bitmap bitmap = BitmapFactory.decodeFile(_path, options );  

I am getting a NullPointerException for bitmap. It means that the bitmap is null. But I have an image ".jpg" file stored in sdcard as "flower2.jpg". What's the problem?

Answer

NikhilReddy picture NikhilReddy · Jan 3, 2012

The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);

or

http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html