从sdcard读取图像文件到位图,为什么我得到NullPointerException?

Smi*_*tha 104 android android-sdcard android-image

如何从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 );  
Run Code Online (Sandbox Code Playgroud)

我得到位图的NullPointerException.这意味着位图为空.但我有一个图像".jpg"文件存储在SD卡中作为"flower2.jpg".有什么问题?

Nik*_*ddy 261

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);
Run Code Online (Sandbox Code Playgroud)

要么

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

  • 什么是`selected_photo`在这里? (3认同)

Ahm*_*lan 27

有用:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);
Run Code Online (Sandbox Code Playgroud)


Jit*_*dra 26

试试这段代码:

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);
Run Code Online (Sandbox Code Playgroud)


Pri*_*sai 5

我编写了以下代码,将图像从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);
Run Code Online (Sandbox Code Playgroud)