我正在使用 MediaStore api 将图像添加到图库。插入有效,但是当我随后查询图像时,datetaken=null
。
以下是我使用 MediaStore 的方式:
private suspend fun saveImageToGallery(
context: Context,
bitmap: Bitmap,
imageName: String
): Uri? = withContext(Dispatchers.IO) {
try {
val contentResolver = context.contentResolver
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, imageName)
put(MediaStore.Images.Media.DESCRIPTION, imageName)
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Images.Media.IS_PENDING, 1)
}
}
// Insert file into MediaStore
val collection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else {
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
}
val galleryFileUri = contentResolver.insert(collection, values)
?: return@withContext null
// Save file to uri from MediaStore
contentResolver.openOutputStream(galleryFileUri).use {
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, it)
}
// Now that we're finished, release the "pending" status, and allow other apps to view the image.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.clear()
values.put(MediaStore.Images.Media.IS_PENDING, 0)
contentResolver.update(galleryFileUri, values, null, null)
}
return@withContext galleryFileUri
} catch (ex: Exception) {
Log.e("MSTEST", "Saving progress pic to gallery failed", ex)
return@withContext null
}
}
这里是重现该问题的项目的链接 https://github.com/jakob-grabner/Media-Store-Example
最佳答案
DATE_TAKEN 被记录为“媒体项目的拍摄时间”。为了提供该 API 描述,他们根据“DateTimeOriginal”Exif 元数据字段填充它。如果正在扫描的文件没有此元数据,则他们无法准确确定捕获文件的时间,因此 DATE_TAKEN 设置为 NULL 以避免误导数据。 因此,必须添加 exif 数据来填充 MediaStore 中的 DATE_TAKEN 字段。
// Add exif data
contentResolver.openFileDescriptor(galleryFileUri, "rw")?.use {
// set Exif attribute so MediaStore.Images.Media.DATE_TAKEN will be set
ExifInterface(it.fileDescriptor)
.apply {
setAttribute(
ExifInterface.TAG_DATETIME_ORIGINAL,
exifDateFormatter.format(Date())
)
saveAttributes()
}
}
关于android - 媒体存储插入 DATE_TAKEN 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57722598/