从SD卡读取图像文件并将其转换为位图时,为什么会出现NullPointerException异常?

110

我该如何从SD卡中读取图像文件并将其转换为位图?

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

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

我在bitmap上遇到了NullPointerException错误。这意味着该bitmap为null。但是我已经在SD卡中存储了一个名为"flower2.jpg"的图片".jpg"文件。问题出在哪里?

4个回答

277

MediaStore API可能会丢弃alpha通道(即解码为RGB565)。如果您有文件路径,只需直接使用BitmapFactory,但告诉它使用保留alpha的格式:

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

或者

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


3
这里的“selected_photo”是什么? - Autonomous
嗨!相册中保存的图像为3840x2160,但通过此方法上传到服务器的图像为1080x1920。 - Shajeel Afzal
@ParagS.Chandakkar 可能是一个 ImageView,在那里您可以显示解码后的文件。 - PinoyCoder

31

它有效:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

29

试试这段代码:

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

6
我编写了以下代码,将SD卡上的图像转换为Base64编码字符串以作为JSON对象发送。它运行良好。
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接