gpt4 book ai didi

java - 将 Intent 图像保存到图库/文件夹

转载 作者:行者123 更新时间:2023-12-01 09:09:57 25 4
gpt4 key购买 nike

我正在尝试将图像保存到我的三星 Galaxy s6 Edge 的文件夹中。我是一名初学者,已经创建了一个应用程序来练习拍摄 Intent 图像并将图像返回到我的应用程序,然后我在应用程序中选择一个图像过滤器并进一步希望将其保存到我的设备中。我不明白为什么它不起作用。我得到的错误是:

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

关于java - 将 Intent 图像保存到图库/文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40982223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com