简体   繁体   中英

Save intent image to gallery/folder

I'm trying to save my images to a folder into my Samsung galaxy s6 edge. I'm a beginner and have created an application to practice take an intent image and return the image to my application where I then choose an image filter and further want to save it to my device. I cant understand why it doesn't work. The error I get is:

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Pictures/Pictures.jpg: open failed: EACCES (Permission denied)

And here is the code:

public void savePhoto(View view) {
        if(currentBitmap != null) {
            File storageLoc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File file = new File(storageLoc, "Pictures.jpg");

            try {
                FileOutputStream fos = new FileOutputStream(file);
                currentBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();

                Context context = getApplicationContext();

                Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                scanIntent.setData(Uri.fromFile(file));
                context.sendBroadcast(scanIntent);

                Toast.makeText(getApplicationContext(), "Your image has been saved!", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getApplicationContext(), "No image taken!", Toast.LENGTH_SHORT).show();
        }
    }

Im using API15 if it have something with that to do. The rest of my code works good without saving images. If someone can see the problem I would be grateful.

Your android version seems to be above Marshmallow. Means you need to check permission at runtime. As log shows Permission denied.

You can do it in two ways

  1. Checking permission by ContextCompat.checkSelfPermission() way
  2. By declaring ANDROID_BUILD_TARGET_SDK_VERSION=22 in gradle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM