为了账号安全,请及时绑定邮箱和手机立即绑定

从sdcard将图像文件读取到位图中,为什么会出现NullPointerException?

从sdcard将图像文件读取到位图中,为什么会出现NullPointerException?

绝地无双 2019-11-12 10:14:18
如何从SD卡读取图像文件到位图中? _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”文件存储在sdcard中,作为“ flower2.jpg”。有什么问题?
查看完整描述

3 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

试试这个代码:


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


查看完整回答
反对 回复 2019-11-12
?
DIEA

TA贡献1820条经验 获得超2个赞

我编写了以下代码,将图像从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);


查看完整回答
反对 回复 2019-11-12
  • 3 回答
  • 0 关注
  • 461 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信