在Android中打开图片时FileNotFound

时间:2015-07-10 08:10:29

标签: android android-camera storage

我正在制作一款需要打开相机拍照的应用。我跟着官方的android guide并且确实像他们说的那样,但我不断收到此错误消息:

Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/Pictures/JPEG_test_-1259913402.jpg: open failed: ENOENT (No such file or directory)

我的代码如下所示:

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            System.err.println("An error occurred: " + ex);
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        //try {
            Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
            System.out.println(imageBitmap);
            testViewer.setImageBitmap(imageBitmap);
            //bc = new BarDecoder(imageBitmap);
        //} catch (NotFoundException | FormatException e){
          //  System.err.println("An error occurred: " + e);
        //}
    } else {
        System.out.println("Cancelled!");
    }
}

public void scanImage(View view){
    dispatchTakePictureIntent();
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = "test";
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    System.out.println("Created!!");
    return image;
}

我可以看到图片确实是在使用文件浏览器时创建的,但我的应用无法找到它们。我还在我的清单文件中包含了这些权限:

<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

关于什么错误的任何想法?

1 个答案:

答案 0 :(得分:0)

通过删除&#34;文件解决了这个问题:&#34;来自mCurrentPhotoPath。 Android的官方指南说这是必要的,但显然这不起作用!