将位图图像保存到画廊 android 10 的特定位置

Jav*_*lon 3 android image save android-10.0

我正在使用此代码:

MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title" , "description");
Run Code Online (Sandbox Code Playgroud)

它运行良好。

问题:

  1. 它会自动在图库中创建一个名为“图片”的文件夹。但我想要不同的名称,例如我的应用程序的名称。
  2. MediaStore 的 insertImage() 函数在 android 10 中折旧

public static String insertImage (ContentResolver cr, String imagePath, String name, String description)

此方法在 API 级别 29 中已弃用。插入图像应使用 MediaColumns#IS_PENDING 执行,它提供了对生命周期的更丰富的控制。

我已经阅读了文档,但实际上并不了解 IS_PENDING 以及如何使用它。

Arj*_*ini 11

尝试这个

private void saveImage(Bitmap bitmap, @NonNull String name) throws IOException {
    boolean saved;
    OutputStream fos;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        ContentResolver resolver = mContext.getContentResolver();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/" + IMAGES_FOLDER_NAME);
        Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        fos = resolver.openOutputStream(imageUri);
    } else {
        String imagesDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM).toString() + File.separator + IMAGES_FOLDER_NAME;

        File file = new File(imagesDir);

        if (!file.exists()) {
            file.mkdir();
        }

        File image = new File(imagesDir, name + ".png");
        fos = new FileOutputStream(image)

    }

    saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();
}
Run Code Online (Sandbox Code Playgroud)