当前位置: 首页 > 面试题库 >

BitmapFactory:即使文件确实存在,也无法解码流:java.io.FileNotFoundException

拓拔坚
2023-03-14
问题内容

我正在创建一个简单的应用程序拍照。这是我的代码

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(android.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)

猜猜该目录是否存在? spoler警报
,确实如此。而且它不像是在之后创建图片BitmapFactory.decodeFile。我真的不明白我在做什么错。一切正常,除非实际上必须显示照片,然后才不显示照片。只是空白。就像WTF
M8一样,我只是想尽我所能,而不必发疯。


问题答案:

替换mImageUri.toString()mImageUri.getPath()

decodeFile 需要一个路径,而不是uri字符串。



 类似资料: