2012-01-03 12 views
92

Come posso leggere un file immagine in bitmap da sdcard?Lettura di un file immagine in bitmap da sdcard, perché sto ricevendo una 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); 

Ricevo una NullPointerException per bitmap. Significa che la bitmap è nulla. Ma ho un file ".jpg" di immagine memorizzato in sdcard come "flower2.jpg". Qual è il problema?

risposta

231

L'API MediaStore probabilmente sta lanciando il canale alfa (ad esempio decodifica su RGB565). Se si dispone di un percorso di file, basta usare BitmapFactory direttamente, ma dire che per utilizzare un formato che conserva alpha:

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

o

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

+3

ciò che è 'selected_photo' qui? –

+3

Your ImageView ... –

+0

Ciao! L'immagine salvata negli album è 3840x2160 ma l'immagine caricata sul server tramite questo metodo è di 1080x1920 –

22

provare questo codice:

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

Ho scritto il seguente codice per convertire un'immagine da sdcard in una stringa codificata Base64 da inviare come oggetto JSON. E funziona benissimo:

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

Funziona:

Bitmap bitmap = BitmapFactory.decodeFile(filePath); 
Problemi correlati