Store image from camera into private app cache dir

2019-04-23 12:26发布

I would like to capture an image from the camera and save it to the private app cache directory. I realize that I have to give the camera app permission to write to my private directory, so I added the FLAG_GRANT_WRITE_URI_PERMISSION flag.

What's happening is, that the camera app opens, I can take the picture, but when i click on the OK button, nothing happens. The camera app stays open. No log output. I guess it's because of a permission problem.

private void getCameraImage() {
    try {
        mTmpFile = File.createTempFile("tmp", ".jpg", getCacheDir());
        Uri imgUri = Uri.fromFile(mTmpFile);
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
        i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // i.setData(imgUri); // if uncommented, i get an ActivityNotFound Exception
        startActivityForResult(i, REQUEST_CAMERA);
    } catch (IOException e) {
        Log.e(TAG, "getCameraImage()", e);
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
    }
}

Any insights, on how I could correct that?

Edit:

When I change the directory to the public SD card, then it works fine.

mTmpFile = File.createTempFile("tmp", ".jpg", Environment.getExternalStorageDirectory());

Thanks Simon

1条回答
Emotional °昔
2楼-- · 2019-04-23 13:01

Instead of passing the Uri to store the picture you can use http://developer.android.com/reference/android/hardware/Camera.html#takePicture(android.hardware.Camera.ShutterCallback, android.hardware.Camera.PictureCallback, android.hardware.Camera.PictureCallback, android.hardware.Camera.PictureCallback)

and get the content in your app memory. From there you will be able to do anything you want.

Do not forget that camera applications are using also the gallery and the gallery app is not allowed to check your private directory.

查看更多
登录 后发表回答