安卓 BitmapFactory:无法解码流:java。木卫一。即使文件实际存在,FileNotFoundException仍然存在
我正在创建一个简单的应用程序来拍照。这是我的密码
Button b1;
ImageView iv;
String TAG = "MAIN ACTIVITY";
File photo;
private Uri mImageUri;
private File createTemporaryFile(String part, String ext) throws Exception {
File externalStorageDirectory = Environment.getExternalStorageDirectory();
File tempDir = new File(externalStorageDirectory + "/cameratest/");
if (!tempDir.exists()) {
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
iv = (ImageView) findViewById(R.id.imageView);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(安卓.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try {
// place where to store camera taken picture
photo = createTemporaryFile("picture", ".jpg");
photo.delete();
} catch (Exception e) {
Log.v(TAG, "Can't create file to take picture!");
Toast.makeText(getApplicationContext(), "Please check SD card! Image shot is impossible!",
Toast.LENGTH_SHORT).show();
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, 0);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG, mImageUri.toString());
Bitmap bitmap = BitmapFactory.decodeFile(mImageUri.toString());
iv.setImageBitmap(bitmap);
}
}
正如您所看到的,我在末尾添加了eLog.d(TAG, mImageUri.toString());
,在logcat(以及FileNotFoundException
)中,我看到了这个目录:
03-27 00:43:30.498 30526-30526/myapplication.example.falcoleo.cameratest1 D/MAIN ACTIVITY: file:///storage/emulated/0/cameratest/picture459838058.jpg
03-27 00:43:30.499 30526-30526/myapplication.example.falcoleo.cameratest1 E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/cameratest/picture459838058.jpg: open failed: ENOENT (No such file or directory)
猜猜这个目录是否存在?
斯波勒警报,it does。而且图像不是在BitmapFactory.decodeFile
之后创建的。我真的不明白我做错了什么。一切正常,除非它实际上必须显示照片,然后它就不显示了。一片空白。就像WTF m8一样,我只是想做好我的工作,不必发疯,你知道的
# 1 楼答案
对我来说,文件路径是错误的,所以我需要得到真正的文件路径
首先
然后返回Uri
这种对文件和uri的转换为我带来了好处。我从行动中得到了一些简单的数据。发送
# 2 楼答案
将
mImageUri.toString()
替换为mImageUri.getPath()
decodeFile
需要路径,而不是uri字符串# 3 楼答案
使用BitmapFactory。解码流而不是位图工厂。解码文件
资料来源https://stackoverflow.com/a/28395036/5714364
# 4 楼答案
删除
file://
,因为decodeFile()需要文件系统路径