From 6b4b15bb871aa894e066c358239ab483e9558abf Mon Sep 17 00:00:00 2001 From: "Alexander \"PapaTutuWawa" Date: Wed, 20 Sep 2023 13:44:52 +0200 Subject: [PATCH] fix(android): "Fix" wrong file extension on image picker usage --- .../org/moxxy/moxxy_native/picker/MimeUtils.kt | 13 +++++++++++++ .../moxxy_native/picker/PickerResultListener.kt | 16 ++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 android/src/main/kotlin/org/moxxy/moxxy_native/picker/MimeUtils.kt diff --git a/android/src/main/kotlin/org/moxxy/moxxy_native/picker/MimeUtils.kt b/android/src/main/kotlin/org/moxxy/moxxy_native/picker/MimeUtils.kt new file mode 100644 index 0000000..2b6b5b5 --- /dev/null +++ b/android/src/main/kotlin/org/moxxy/moxxy_native/picker/MimeUtils.kt @@ -0,0 +1,13 @@ +package org.moxxy.moxxy_native.picker + +object MimeUtils { + // A reverse-mapping of image mime types to their commonly used file extension. + val imageMimeTypesToFileExtension = mapOf( + "image/png" to ".png", + "image/apng" to ".apng", + "image/avif" to ".avif", + "image/gif" to ".gif", + "image/jpeg" to ".jpeg", + "image/webp" to ".webp", + ) +} diff --git a/android/src/main/kotlin/org/moxxy/moxxy_native/picker/PickerResultListener.kt b/android/src/main/kotlin/org/moxxy/moxxy_native/picker/PickerResultListener.kt index 25d2358..f518c4f 100644 --- a/android/src/main/kotlin/org/moxxy/moxxy_native/picker/PickerResultListener.kt +++ b/android/src/main/kotlin/org/moxxy/moxxy_native/picker/PickerResultListener.kt @@ -6,7 +6,7 @@ import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build -import android.provider.OpenableColumns +import android.provider.MediaStore.Images import android.util.Log import io.flutter.plugin.common.PluginRegistry.ActivityResultListener import org.moxxy.moxxy_native.AsyncRequestTracker @@ -29,10 +29,22 @@ class PickerResultListener(private val context: Context) : ActivityResultListene private fun queryFileName(context: Context, uri: Uri): String { var result: String? = null if (uri.scheme == "content") { + val projection = arrayOf( + Images.Media._ID, + Images.Media.MIME_TYPE, + Images.Media.DISPLAY_NAME, + ) val cursor = context.contentResolver.query(uri, null, null, null, null) cursor.use { cursor -> if (cursor != null && cursor.moveToFirst()) { - result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) + val mimeType = cursor.getString(cursor.getColumnIndex(Images.Media.MIME_TYPE)) + val displayName = cursor.getString(cursor.getColumnIndex(Images.Media.DISPLAY_NAME)) + val fileExtension = MimeUtils.imageMimeTypesToFileExtension[mimeType] + + // Note: This is a workaround for the Dart image library failing to parse the file + // because displayName somehow is always ".jpg", which confuses image. + result = if (fileExtension != null) "$displayName$fileExtension" else displayName + Log.d(TAG, "Returning $result as filename (MIME: $mimeType)") } } }