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

时光怂恿深爱的人放手 提交于 2019-11-26 03:07:30

问题


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?


回答1:


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




回答2:


It works:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);



回答3:


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);



回答4:


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);


来源:https://stackoverflow.com/questions/8710515/reading-an-image-file-into-bitmap-from-sdcard-why-am-i-getting-a-nullpointerexc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!