Android:捕获并存储图片

时间:2014-11-12 10:22:41

标签: android file-io android-permissions

我正在关注this tutorial拍照,显示缩略图并将完整图片存储在我的应用程序可用的本地公共存储空间中。

问题:尝试访问我的应用程序的本地存储时,EACCESS(权限被拒绝)

11-12 10:36:30.765    3746-3746/com.test.example.photo W/System.err﹕ java.io.IOException: open failed: EACCES (Permission denied)
11-12 10:36:30.765    3746-3746/com.test.example.photo W/System.err﹕ at java.io.File.createNewFile(File.java:948)
11-12 10:36:30.765    3746-3746/com.test.example.photo W/System.err﹕ at java.io.File.createTempFile(File.java:1013)

我看过this question但它似乎已经过时了,因为今天没有任何解决方案可以使用了。 This question也没有提供有效的解决方案。我见过和尝试的其他结果和解决方案似乎只是含糊不清。

我的清单权限

</application>
    <!-- PERMISSIONS -->
    <permission
        android:name="android.hardware.Camera.any"
        android:required="true" />
    <permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:required="true" />
    <!-- android:maxSdkVersion="18" seemingly does nothing-->
</manifest>

崩溃的方法

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";

    //THIS IS WHERE IT CRASHES
    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();
    return image;
}

我正在使用i9250 Galaxy Nexus 3手机来运行示例,因为我的模拟器没有摄像头并自动使用了元素。我的目标SDK是16,我已将我的构建工具和Android Studio更新到最新版本。

我觉得我在这里遗漏了一些明显的东西,因为拍照在应用程序中非常常见,我无法想象它不适合所有人,但是我被困住了,我很感激你的指导。我对android很新,我主要使用的文献是Beginning Android 4 Game Programming,Beginning Android 4和Pro Android 4。

感谢您的时间!

3 个答案:

答案 0 :(得分:3)

感谢大家的帮助,它现在有效!

显然我正在使用需要权限的SD卡存储,如permission vs uses-permisson中所述,而不是本地沙盒存储,不需要从API级别19开始的权限。

SD卡访问,需要写入权限:Environment.getExternalStoragePublicDirectory

适用于您应用的沙盒本地存储空间:getExternalFilesDir

我将此代码用于API级别16,它应该只需要很少的工作来实现和更改,但是如果遇到问题,请留言并且我会尝试帮助或澄清。

大多数解释都在代码中作为评论

    //OnClick hook, requires implements View.OnClickListener to work
    public void takePicture(View v) {
        dispatchTakePictureIntent();
    }

    private void dispatchTakePictureIntent() {
        //Create intent to capture an image from the camera
        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 directory File where the photo should go, do NOT try to create the image file itself
            File photoFile = null;
            try {
                //mCurrentPhotoPath is a File outside of the methods, so all methods know the last directory for the last picture taken
                mCurrentPhotoPath = createImageFile();
                photoFile = mCurrentPhotoPath;
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                //photoFile MUST be a directory or the camera will hang on an internal
                //error and will refuse to store the picture,
                //resulting in not being able to to click accept
                //MediaStore will automatically store a jpeg for you in the specific directory and add the filename to the path
                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) {
            //unique name, can be pretty much whatever you want
            imageId = generateImageId(); 
            //Get file.jpg as bitmap from MediaStore's returned File object
            Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath.getAbsolutePath()); 
            //resize it to fit the screen
            imageBitmap = Bitmap.createScaledBitmap(imageBitmap,300,300,false); 
            //Some ImageView in your layout.xml
            ImageView imageView = (ImageView)findViewById(R.id.imageView); 
            imageView.setImageBitmap(imageBitmap);
            Bitmap thumbnail =  makeThumbnail(mCurrentPhotoPath);
            ImageView thumbnail = (ImageView)findViewById(R.id.thumbnail); 
            thumbnail.setImageBitmap(imageBitmap);
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        //completely optional subdirectory structure
        storageDir = new File(storageDir, "custom_directory");
        return storageDir;
    }    

    private Bitmap makeThumbnail(File currentPhotoPath) {
        // Get the dimensions of the View, I strongly recommend creating a <dimens> resource for dip scaled pixels
        int targetW = 45;
        int targetH = 80;

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(currentPhotoPath.getAbsolutePath(), bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath.getAbsolutePath(), bmOptions);
        return bitmap;
    }

    private long generateImageId() {
        return Calendar.getInstance().getTimeInMillis();
    }

Android 5.0,API 21,将使用Camera2 API,其中所有这些将远离我的理解隐藏。你可以阅读它here

答案 1 :(得分:1)

试试这个:

private File getDir() {
File sdDir = Environment
  .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "Your_photo_dir_here");

}

然后:

 File pictureFileDir = getDir();

if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

  Log.d("TAG", "Can't create directory to save image.");
  return;

}


SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "myphoto_" + date + ".jpg";

String filename = pictureFileDir.getPath() + File.separator + photoFile;

File pictureFile = new File(filename);

try {
  FileOutputStream fos = new FileOutputStream(pictureFile);
  fos.write(data);
  fos.close();

} catch (Exception error) {
  Log.d("TAG", "File" + filename + "not saved: "
      + error.getMessage());

}

答案 2 :(得分:-1)

使用uses-permission代替权限标记 在清单中添加此内容

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />