【问题标题】:Save bitmap image to specific location of gallery android 10将位图图像保存到画廊 android 10 的特定位置
【发布时间】:2020-12-25 19:50:02
【问题描述】:

我正在使用此代码:

MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title" , "description");

它运行良好。

问题:

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

公共静态字符串 insertImage (ContentResolver cr, 字符串图像路径, 字符串名称, 字符串描述)

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

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

【问题讨论】:

  • 您不想保存在图库中,而是在媒体商店中查看您的代码。
  • 您只能将您的应用程序文件夹创建为 Android 10 下众所周知的 Documents、Download、DCIM、Pictures ... 目录之一的子目录。

标签: android image save android-10.0


【解决方案1】:

试试这个代码:-

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();
}

【讨论】:

  • 您没有为 Android 10 使用 IS_PENDING 两次。OP 要求这样做。
  • @blackapps 如何防止多次插入相同的图像,当这个函数被调用两次时为同一个位图
  • @mad_lad 一个人可以保存同一个位图一百次。没有人会检查位图是否与昨天使用的相同。
  • @blackapps 这是我的问题,每当用户单击我的应用程序中的保存图像按钮时,都会调用上述函数。如果用户再次点击保存图片按钮,那么同一张图片将被保存两次。如何防止此问题。
  • 禁用按钮。
猜你喜欢
  • 2016-08-06
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多