Java 如何使用 MediaStore 在 Android Q 中保存图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56904485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:17:33  来源:igfitidea点击:

How to save an image in Android Q using MediaStore?

javaandroidimagekotlinmediastore

提问by Omar Abdelhafiz

Here is a link to the new Android Q Scoped Storage.

这是新的 Android Q Scoped Storage的链接。

According to this Android Developers Best Practices Blog, storing shared media files(which is my case) should be done using the MediaStoreAPI.

根据这个 Android Developers Best Practices Blogstoring shared media files(这是我的情况)应该使用MediaStoreAPI来完成。

Digging into the docs and I cannot find a relevant function.

深入研究文档,我找不到相关的功能。

Here is my trial in Kotlin:

这是我在 Kotlin 中的试验:

val bitmap = getImageBitmap() // I have a bitmap from a function or callback or whatever
val name = "example.png" // I have a name

val picturesDirectory = getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!

// Make sure the directory "Android/data/com.mypackage.etc/files/Pictures" exists
if (!picturesDirectory.exists()) {
    picturesDirectory.mkdirs()
}

try {
    val out = FileOutputStream(File(picturesDirectory, name))
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)

    out.flush()
    out.close()

} catch(e: Exception) {
    // handle the error
}

The result is that my image is saved here Android/data/com.mypackage.etc/files/Pictures/example.pngas described in the Best Practices Blog as Storing app-internal files

结果是我的图像保存在这里Android/data/com.mypackage.etc/files/Pictures/example.png,如最佳实践博客中所述Storing app-internal files



My question is:

我的问题是:

How to save an image using the MediaStore API?

如何使用 MediaStore API 保存图像?



Answers in Java are equally acceptable.

Java 中的答案同样可以接受。

Thanks in Advance!

提前致谢!



EDIT

编辑

Thanks to PerracoLabs

感谢 PerracoLabs

That really helped!

那真的很有帮助!

But there are 3 more points.

但是还有3点。

Here is my code:

这是我的代码:

val name = "Myimage"
val relativeLocation = Environment.DIRECTORY_PICTURES + File.pathSeparator + "AppName"

val contentValues  = ContentValues().apply {
    put(MediaStore.Images.ImageColumns.DISPLAY_NAME, name)
    put(MediaStore.MediaColumns.MIME_TYPE, "image/png")

    // without this part causes "Failed to create new MediaStore record" exception to be invoked (uri is null below)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        put(MediaStore.Images.ImageColumns.RELATIVE_PATH, relativeLocation)
    }
}

val contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
var stream: OutputStream? = null
var uri: Uri? = null

try {
    uri = contentResolver.insert(contentUri, contentValues)
    if (uri == null)
    {
        throw IOException("Failed to create new MediaStore record.")
    }

    stream = contentResolver.openOutputStream(uri)

    if (stream == null)
    {
        throw IOException("Failed to get output stream.")
    }

    if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream))
    {
        throw IOException("Failed to save bitmap.")
    }


    Snackbar.make(mCoordinator, R.string.image_saved_success, Snackbar.LENGTH_INDEFINITE).setAction("Open") {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_VIEW
        intent.data = contentUri
        startActivity(Intent.createChooser(intent, "Select Gallery App"))
    }.show()

} catch(e: IOException) {
    if (uri != null)
    {
        contentResolver.delete(uri, null, null)
    }

    throw IOException(e)

}
finally {
    stream?.close()
}

1- The image saved doesn't get its correct name "Myimage.png"

1- 保存的图像没有得到正确的名称“Myimage.png”

I tried using "Myimage" and "Myimage.PNG" but neither worked.

我尝试使用“Myimage”和“Myimage.PNG”,但都没有奏效。

The image always gets a name made up of numbers like:

图像的名称总是由数字组成,例如:

1563468625314.jpg

1563468625314.jpg

Which bring us to the second problem:

这给我们带来了第二个问题:

2- The image is saved as jpgeven though I compress the bitmap in the format of png.

2-jpg即使我以png.

Not a big issue. Just curious why.

不是什么大问题。只是好奇为什么。

3- The relativeLocation bit causes an exception on Devices less than Android Q. After surrounding with the "Android Version Check" if statement, the images are saved directly in the root of the Picturesfolder.

3-relativeLocation 位在低于 Android Q 的设备上导致异常。用“Android 版本检查”if 语句包围后,图像直接保存在Pictures文件夹的根目录中。

Another Thank you.

另一个谢谢。



EDIT 2

编辑 2

Changed to:

变成:

uri = contentResolver.insert(contentUri, contentValues)
if (uri == null)
{
    throw IOException("Failed to create new MediaStore record.")
}

val cursor = contentResolver.query(uri, null, null, null, null)
DatabaseUtils.dumpCursor(cursor)
cursor!!.close()

stream = contentResolver.openOutputStream(uri)

Here are the logs

这是日志

I/System.out: >>>>> Dumping cursor android.content.ContentResolver$CursorWrapperInner@76da9d1
I/System.out: 0 {
I/System.out:    _id=25417
I/System.out:    _data=/storage/emulated/0/Pictures/1563640732667.jpg
I/System.out:    _size=null
I/System.out:    _display_name=Myimage
I/System.out:    mime_type=image/png
I/System.out:    title=1563640732667
I/System.out:    date_added=1563640732
I/System.out:    is_hdr=null
I/System.out:    date_modified=null
I/System.out:    description=null
I/System.out:    picasa_id=null
I/System.out:    isprivate=null
I/System.out:    latitude=null
I/System.out:    longitude=null
I/System.out:    datetaken=null
I/System.out:    orientation=null
I/System.out:    mini_thumb_magic=null
I/System.out:    bucket_id=-1617409521
I/System.out:    bucket_display_name=Pictures
I/System.out:    width=null
I/System.out:    height=null
I/System.out:    is_hw_privacy=null
I/System.out:    hw_voice_offset=null
I/System.out:    is_hw_favorite=null
I/System.out:    hw_image_refocus=null
I/System.out:    album_sort_index=null
I/System.out:    bucket_display_name_alias=null
I/System.out:    is_hw_burst=0
I/System.out:    hw_rectify_offset=null
I/System.out:    special_file_type=0
I/System.out:    special_file_offset=null
I/System.out:    cam_perception=null
I/System.out:    cam_exif_flag=null
I/System.out: }
I/System.out: <<<<<

I noticed the titleto be matching the name so I tried adding:

我注意到title要匹配名称,所以我尝试添加:

put(MediaStore.Images.ImageColumns.TITLE, name)

put(MediaStore.Images.ImageColumns.TITLE, name)

It still didn't work and here are the new logs:

它仍然没有工作,这里是新的日志:

I/System.out: >>>>> Dumping cursor android.content.ContentResolver$CursorWrapperInner@51021a5
I/System.out: 0 {
I/System.out:    _id=25418
I/System.out:    _data=/storage/emulated/0/Pictures/1563640934803.jpg
I/System.out:    _size=null
I/System.out:    _display_name=Myimage
I/System.out:    mime_type=image/png
I/System.out:    title=Myimage
I/System.out:    date_added=1563640934
I/System.out:    is_hdr=null
I/System.out:    date_modified=null
I/System.out:    description=null
I/System.out:    picasa_id=null
I/System.out:    isprivate=null
I/System.out:    latitude=null
I/System.out:    longitude=null
I/System.out:    datetaken=null
I/System.out:    orientation=null
I/System.out:    mini_thumb_magic=null
I/System.out:    bucket_id=-1617409521
I/System.out:    bucket_display_name=Pictures
I/System.out:    width=null
I/System.out:    height=null
I/System.out:    is_hw_privacy=null
I/System.out:    hw_voice_offset=null
I/System.out:    is_hw_favorite=null
I/System.out:    hw_image_refocus=null
I/System.out:    album_sort_index=null
I/System.out:    bucket_display_name_alias=null
I/System.out:    is_hw_burst=0
I/System.out:    hw_rectify_offset=null
I/System.out:    special_file_type=0
I/System.out:    special_file_offset=null
I/System.out:    cam_perception=null
I/System.out:    cam_exif_flag=null
I/System.out: }
I/System.out: <<<<<

And I can't change date_addedto a name.

而且我不能改date_added名字。

And MediaStore.MediaColumns.DATAis deprecated.

并且MediaStore.MediaColumns.DATA已弃用。

Thanks in Advance!

提前致谢!

采纳答案by PerracoLabs

Try the next method. Android Q already takes care of creating the folders if they don't exist. The example is hard-coded to output into the Pictures folder. If you need a sub-folder then append the sub-folder name as next:

尝试下一个方法。如果文件夹不存在,Android Q 已经负责创建文件夹。该示例是硬编码的以输出到图片文件夹中。如果您需要一个子文件夹,则将子文件夹名称附加如下:

final String relativeLocation = Environment.DIRECTORY_PICTURES + File.separator + “YourSubforderName”;

Consider that the compress format should be related to the mime-type parameter. For example, with a JPEG compress format the mime-type would be "image/jpeg", and so on.

考虑压缩格式应该与 mime-type 参数相关。例如,对于 JPEG 压缩格式,mime-type 将是“image/jpeg”,依此类推。

private void saveBitmap(@NonNull final Context context, @NonNull final Bitmap bitmap,
                        @NonNull final Bitmap.CompressFormat format, @NonNull final String mimeType,
                        @NonNull final String displayName) throws IOException
{
    final String relativeLocation = Environment.DIRECTORY_PICTURES;

    final ContentValues  contentValues = new ContentValues();
    contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName);
    contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
    contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation);

    final ContentResolver resolver = context.getContentResolver();

    OutputStream stream = null;
    Uri uri = null;

    try
    {
        final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        uri = resolver.insert(contentUri, contentValues);

        if (uri == null)
        {
            throw new IOException("Failed to create new MediaStore record.");
        }

        stream = resolver.openOutputStream(uri);

        if (stream == null)
        {
            throw new IOException("Failed to get output stream.");
        }

        if (bitmap.compress(format, 95, stream) == false)
        {
            throw new IOException("Failed to save bitmap.");
        }
    }
    catch (IOException e)
    {
        if (uri != null)
        {
            // Don't leave an orphan entry in the MediaStore
            resolver.delete(uri, null, null);
        }

        throw e;
    }
    finally
    {
        if (stream != null)
        {
            stream.close();
        }
    }
}

回答by Rachit Vohera

private void saveImage(Bitmap bitmap, @NonNull String name) throws IOException {
    OutputStream fos;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        ContentResolver resolver = getContentResolver();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name + ".jpg");
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
        Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
    } else {
        String imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
        File image = new File(imagesDir, name + ".jpg");
        fos = new FileOutputStream(image);
    }
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    Objects.requireNonNull(fos).close();
}

Image will store in Pictures Folder @ root level

图像将存储在图片文件夹@根级别

see in live https://youtu.be/695HqaiwzQ0i created tutorial

现场观看https://youtu.be/695HqaiwzQ0我创建的教程