2012-01-03 3 views
92

イメージファイルをsdcardからビットマップに読み込むにはどうすればよいですか?イメージファイルをsdcardからビットマップに読み込むと、なぜ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); 

ビットマップにNullPointerExceptionが発生します。これは、ビットマップがヌルであることを意味します。しかし、私は画像 ".jpg"ファイルを "flower2.jpg"としてsdcardに保存しています。どうしたの?

答えて

231

MediaStore APIはおそらくアルファチャンネルを捨ててしまっています(つまり、RGB565へのデコード)。あなたはファイルパスをお持ちの場合は、単に直接BitmapFactoryを使用しますが、アルファを保持する形式を使用することを教え:

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'されますか? –

+3

ImageView ... –

+0

こんにちは!アルバムに保存された画像は3840x2160ですが、この方法でサーバーにアップロードされる画像は1080x1920 –

22

は、このコードを試してみてください。

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

イメージをsdcardから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); 
20

それは動作します: `ここで何を

Bitmap bitmap = BitmapFactory.decodeFile(filePath); 
関連する問題