【发布时间】:2019-12-12 21:26:40
【问题描述】:
我需要将图像保存到相机文件夹,但由于不推荐使用 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 的操作系统的节省?
【问题讨论】:
-
“但它看起来不准确”——对我来说似乎没问题。在 Q 上,您可以在写出内容时使用
IS_PENDING。 “如何优化低于 Q 的操作系统的节省?” -- 除了fileHashCode这对线之外,你所拥有的似乎是合理的。 -
@CommonsWare,没关系我用不同的方式保存它?没有办法像 Q 那样保存图像?我正在寻找另一个用于插入的 URI,但什么也没有。
-
"所以我可以用不同的方式保存它吗?" - 当然。 “有没有办法像Q一样保存图像?” -- 不在特定位置。
RELATIVE_PATH在 Q 之前不存在。请注意,MediaStore不会立即在代码的旧于 Q 分支中知道您的图像。如果这对您很重要,请使用MediaScannerConnection.scanFile()。 -
@pic:使用
Uri,因为没有可以使用的文件系统路径。 Glide、Picasso 和其他优秀的图像加载库可以显示由MediaStoreUri标识的图像。或者,使用ContentResolver和openInputStream()自己读取图像字节。 -
@pic:您需要查询
MediaStore。如果您对此过程有任何疑问,并且找不到有关它的现有答案,请提出单独的 Stack Overflow 问题。
标签: android android-10.0