我需要将一张图片保存到相机文件夹中,但由于Android Q中getExternalStoragePublicDirectory方法已被弃用,我采用了另一种方式。 现有的方法(接收位图和它的名称):
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);
OutputStream fos = resolver.openOutputStream(imageUri);
saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} 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"
);
final long fileHashCode = image.hashCode();
Logger.d(TAG, "saveImage, saving image file, hashCode = " + fileHashCode);
FileOutputStream fos = new FileOutputStream(image);
saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
那对于所需的所有操作系统版本都完美适用,但它看起来不准确,我想找到一种更常见的方式。我尝试了调整内容值或尝试与 Q 类似的方法,但都不起作用。我在这里看到了很多问题,但没有一个可以帮助我。
问题是如何优化低于 Q 的操作系统的保存?
RELATIVE_PATH
是不存在的。请注意,在早于 Q 的代码分支中,MediaStore
不会立即知道您的图像。如果这对您很重要,请使用MediaScannerConnection.scanFile()
。 - CommonsWareUri
,因为没有文件系统路径可用。 Glide、Picasso和其他优秀的图像加载库可以显示由MediaStore
Uri
标识的图像。或者,使用ContentResolver
和openInputStream()
自己读取图像字节。 - CommonsWareMediaStore
。如果您对此过程有疑问,并且找不到现有的答案,请提出一个单独的 Stack Overflow 问题。 - CommonsWare