0

我正在尝试拍摄图像,将其优化为 65% jpeg 并将其保存到手机存储中。下面的代码在我的nexus 上运行良好,但在最后一行返回了一个空指针异常。

知道我做错了什么吗?谢谢

// image passed in from camera
Bitmap bm = BitmapFactory.decodeFile(selectedImagePath, opts);

// create output
FileOutputStream fileOutputStream = null;

// create filename & directory
String nameFile = "ms" + String.valueOf(System.currentTimeMillis())+ ".jpg";
String directory = "/DCIM/MySeats/";

// try creating the directories if they don't already exist         
File file = new File(Environment.getExternalStorageDirectory(),directory);
file.mkdirs();

// prep output
fileOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+ directory + nameFile);
optimizedImagePath = Environment.getExternalStorageDirectory().toString()+ directory + nameFile;

// write file through a buffered stream
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);

// This line causes a null pointer exception on some phones?
// What am I missing?
bm.compress(CompressFormat.JPEG, 65, bos);
4

2 回答 2

0

最后一行出现空指针异常是由于最后一行使用的两个变量为空

检查 bm != null 检查 bos!= null

于 2011-02-21T16:25:18.400 回答
0

我将假设您正在启动本机相机应用程序,并且此代码可能都来自 onActivityResult() 方法。您的问题可能是具有运营商特定版本的几部手机忽略了MediaStore.EXTRA_OUTPUT参数,只是在返回的Intent. 这意味着您期望的路径上的图像为空,您getData()有时必须从意图中提取图像。

于 2011-02-21T18:22:52.887 回答