从 sdcard 将图像文件读入位图,为什么会出现 NullPointerException?

如何从 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 );

我得到一个位图的 NullPointerException。这意味着位图为空。但我有一个形象”。“ jpg”文件存储在 sdcard 中,名为“ flower 2.jpg”。有什么问题吗?

188295 次浏览

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

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

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

It works:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);