媒体商店插入 DATE_TAKEN 始终为空

Media Store insert DATE_TAKEN is always null

我正在使用 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
    }
}

这是一个 link 重现问题的项目 https://github.com/jakob-grabner/Media-Store-Example

DATE_TAKEN 被记录为 "The time the media item was 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()
                }
        }