2012-01-03 25 views
92

Làm cách nào để đọc tệp hình ảnh vào bitmap từ sdcard?Đọc tệp hình ảnh thành bitmap từ sdcard, tại sao tôi nhận được NullPointerException?

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

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

Tôi nhận được NullPointerException cho bitmap. Nó có nghĩa là bitmap là null. Nhưng tôi có một hình ảnh ".jpg" tập tin được lưu trữ trong sdcard là "flower2.jpg". Có chuyện gì vậy?

Trả lời

231

API MediaStore có thể đang loại bỏ kênh alpha (tức là giải mã thành RGB565). Nếu bạn có một đường dẫn tập tin, chỉ cần sử dụng BitmapFactory trực tiếp, nhưng nói cho nó để sử dụng một định dạng mà bảo alpha:

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

hoặc

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

+3

gì là 'selected_photo' đây? –

+3

ImageView của bạn ... –

+0

Xin chào! Hình ảnh được lưu trong Album là 3840x2160 nhưng hình ảnh được tải lên máy chủ thông qua phương thức này là 1080x1920 –

22

Hãy thử mã này:

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

Tôi đã viết đoạn mã sau để chuyển đổi một hình ảnh từ sdcard thành chuỗi mã hóa Base64 để gửi dưới dạng đối tượng JSON. Và nó hoạt động tốt:

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

Nó hoạt động:

Bitmap bitmap = BitmapFactory.decodeFile(filePath); 
Các vấn đề liên quan