将意图图像保存到 gallery/folder

Save intent image to gallery/folder

我正在尝试将我的图像保存到我的 Samsung galaxy s6 edge 的文件夹中。我是初学者,创建了一个应用程序来练习拍摄意图图像并将 return 图像添加到我的应用程序中,然后我在其中选择一个图像过滤器并进一步想将其保存到我的设备中。我不明白为什么它不起作用。我得到的错误是:

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Pictures/Pictures.jpg: 打开失败:EACCES(权限被拒绝)

这是代码:

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();
        }
    }

我正在使用 API15,如果它有什么用的话。我的其余代码无需保存图像即可正常工作。如果有人能看到问题,我将不胜感激。

您的 android 版本似乎高于 Marshmallow。意味着您需要在运行时检查权限。如日志所示,权限被拒绝。

您可以通过两种方式完成

  1. 通过 ContextCompat.checkSelfPermission() 方式检查权限
  2. 通过在 gradle 中声明 ANDROID_BUILD_TARGET_SDK_VERSION=22