当前位置: 首页 > 知识库问答 >
问题:

java.io.ioException:拒绝在sdcard上保存位图图像的权限[重复]

云浩然
2023-03-14
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
java.io.FileNotFoundException: /storage/emulated/0/Horoscope/IMG_1569837709260.png (Permission denied)
public static void saveImage(Bitmap finalBitmap, Activity activity) {
        File myDir = new File(Environment.getExternalStorageDirectory().getPath() + "/Horoscope");
        myDir.mkdirs();
        String fname = "IMG_" + System.currentTimeMillis() + ".png";
        File file = new File(myDir, fname);

        try (FileOutputStream out = new FileOutputStream(file)) {
            finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
            MediaStore.Images.Media.insertImage(activity.getContentResolver(), file.getPath(), fname, "description");
            Toast.makeText(activity, "Saved.", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

错误异常

java.io.FileNotFoundException: /storage/emulated/0/Horoscope/IMG_1569837709260.png (Permission denied)
            at java.io.FileOutputStream.open0(Native Method)
            at java.io.FileOutputStream.open(FileOutputStream.java:287)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:223)
            at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
            at com.example.opencv.utils.Constant.saveImage(Constant.java:378)
            at com.example.opencv.activity.ForeignerMakerResultActivity$3.onClick(ForeignerMakerResultActivity.java:106)
            at android.view.View.performClick(View.java:6319)
            at android.view.View$PerformClick.run(View.java:24955)
            at android.os.Handler.handleCallback(Handler.java:790)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:192)
            at android.app.ActivityThread.main(ActivityThread.java:6760)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)

共有1个答案

郦磊
2023-03-14

您必须在tun时间检查并授予存储权限。

除此之外,您还需要为SDK版本>23添加以下代码

扩展应用程序类,并将onCreate()方法放在代码下面

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
    if (Build.VERSION.SDK_INT > 23) {
        builder.detectFileUriExposure();
    }
<application
    android:name="com.gym.client.WebURLApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:theme="@style/AppTheme">
</application>
 类似资料: