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

AndroidAndroid SdcardAndroid Image

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

It works:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

Solution 3 - Android

Try this code:

Bitmap bitmap = null;
File f = new File(_path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
    bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}         
image.setImageBitmap(bitmap);

Solution 4 - Android

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSmithaView Question on Stackoverflow
Solution 1 - AndroidNikhilReddyView Answer on Stackoverflow
Solution 2 - AndroidAhmad ArslanView Answer on Stackoverflow
Solution 3 - AndroidJitendraView Answer on Stackoverflow
Solution 4 - AndroidPriyank DesaiView Answer on Stackoverflow