web-dev-qa-db-fra.com

Lire un fichier image en bitmap depuis sdcard, pourquoi ai-je une exception NullPointerException?

Comment lire un fichier image en bitmap depuis 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 );  

Je reçois une exception NullPointerException pour bitmap. Cela signifie que le bitmap est null. Mais j'ai un fichier image ".jpg" enregistré dans sdcard sous le nom "flower2.jpg". Quel est le problème?

104
Smitha

L’API MediaStore jette probablement le canal alpha (décodage RGB565). Si vous avez un chemin de fichier, utilisez simplement BitmapFactory directement, mais dites-lui d'utiliser un format qui préserve l'alpha:

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

ou

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

258
NikhilReddy

Essayez ce 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);
26
Jitendra

Ça marche:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);
26
Ahmad Arslan

J'ai écrit le code suivant pour convertir une image de sdcard en une chaîne codée en Base64 à envoyer en tant qu'objet JSON. Et cela fonctionne très bien:

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