java.lang.IllegalStateException:无法构建唯一文件:/storage/emulated/0/Pictures Title image/jpeg Android 10(Samsung note 10+)

Abr*_*hew 6 android image android-camera illegalstateexception android-10.0

我正在使用以下代码从相机获取图像 uri

public static Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}
Run Code Online (Sandbox Code Playgroud)

Abr*_*hew 16

这仅在 android 10 中作为错误出现,早期版本使用此代码运行良好。无论版本如何,我都将 insertImage() 中的硬编码“标题”更改为

public static Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, **"IMG_" + Calendar.getInstance().getTime(),** null);
        return Uri.parse(path);
    }
Run Code Online (Sandbox Code Playgroud)

现在它是一个带有 IMG_+ 时间的标签


小智 6

是的,此错误仅在 Android 10 中存在,并且仅在某些设备型号中存在。

所有图像都被存储为“标题”,但需要一个唯一的名称。

如果您尝试同时存储多个图像,则接受的答案并不总是生成唯一的名称。

所以更换insertImage电话:

String path = MediaStore.Images.Media.insertImage(
    inContext.getContentResolver(), inImage, "IMG_" + System.currentTimeMillis(), null
);
Run Code Online (Sandbox Code Playgroud)