Arcyno
Arcyno

Reputation: 4603

Android : save/open picture taken from camera intent

I have a camera intent that takes a picture that I want to save anywhere as a temp file :

File photo = new File(Environment.getExternalStorageDirectory(), "myTempPicture.jpg");
imageUri =  Uri.fromFile(photo);

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,0);

(Maybe the choice of Storage is not the right one) Then after the picture was taken, I need to open it to process it :

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
        process(bitmap, false);
    }catch(Exception e){
         Log.d("exception : ", e.toString());
    }
}

But I get the following Exception : java.io.FileNotFoundException: /storage/emulated/0/savedImage.jpg (Permission denied).

What went wrong ?


My Manifest file contains :

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

Upvotes: 1

Views: 149

Answers (1)

Ashwini Saini
Ashwini Saini

Reputation: 1374

with android 6.0+ or SDK 23 and above you have to ask runtime permission in your activity

here an example how you can do that, here 1 is your request code

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
        }

and then you should check if user granted permission

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

for more detailed guide about runtime request have a look here at official documentation

Upvotes: 1

Related Questions