【问题标题】:java.lang.IllegalStateException: Failed to build unique file: /storage/emulated/0/Pictures Title image/jpeg Android 10(Samsung note 10+)java.lang.IllegalStateException:无法构建唯一文件:/storage/emulated/0/Pictures Title image/jpeg Android 10(Samsung note 10+)
【发布时间】:2020-08-22 12:38:40
【问题描述】:

我正在使用下面的代码从相机获取图像 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);
}

【问题讨论】:

  • 你有存储权限吗?
  • 有读写权限

标签: android image android-camera illegalstateexception android-10.0


【解决方案1】:

这仅在 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);
    }

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

【讨论】:

    【解决方案2】:

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

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

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

    所以替换insertImage调用:

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

    【讨论】:

      【解决方案3】:

      是的,我有 Android 11,当我从相机上传图像时,它无法识别路径。 我已经解决了这个问题

        Random rand = new Random();
                int randNo = rand.nextInt(1000);
      String path = MediaStore.Images.Media.insertImage(
          inContext.getContentResolver(), inImage, "IMG_" + randNo, null
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-11
        • 2022-10-02
        • 2021-11-05
        相关资源
        最近更新 更多