【发布时间】:2021-10-21 18:49:53
【问题描述】:
我想将图像保存到Shared Storage,适用于 Android 10 或更高版本,并告诉用户文件名。
ContentResolver cr = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put( MediaStore.MediaColumns.DISPLAY_NAME, file_name );
contentValues.put( MediaStore.MediaColumns.MIME_TYPE, "image/png");
contentValues.put( MediaStore.MediaColumns.RELATIVE_PATH,
Environment.DIRECTORY_PICTURES+"/"+context.getString( R.string.app_name ));
uri = cr.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
out = cr.openOutputStream(uri);
// and write a bitmap by compress method
它工作正常。但是如果存在同名的图像,例如“image.png”,那么系统会创建文件名“image (1).png”、“image (2).png”等。 如何获得真实的文件名? 还有一个。如何获取图像文件大小以获取信息。我现在使用这个,但不确定这是正确的做法。
AssetFileDescriptor afd = context.getContentResolver().openAssetFileDescriptor(uri , "r");
info_out.size = afd.getLength();
afd.close();
【问题讨论】:
-
使用
DocumentFile作为显示名称和长度。 -
先检查文件是否已经存在。如果是这样,如果你想覆盖文件,请使用它的 uri。
-
@blackapps 我无法检查,我还没有 uri。
-
检查:您应该在媒体存储中查询该文件名和相对路径。如果您获得 uri,则该文件存在。否则不会。
标签: android android-contentresolver