fix(android): "Fix" wrong file extension on image picker usage

This commit is contained in:
PapaTutuWawa 2023-09-20 13:44:52 +02:00
parent c905b3242d
commit 6b4b15bb87
2 changed files with 27 additions and 2 deletions

View File

@ -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",
)
}

View File

@ -6,7 +6,7 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.net.Uri import android.net.Uri
import android.os.Build import android.os.Build
import android.provider.OpenableColumns import android.provider.MediaStore.Images
import android.util.Log import android.util.Log
import io.flutter.plugin.common.PluginRegistry.ActivityResultListener import io.flutter.plugin.common.PluginRegistry.ActivityResultListener
import org.moxxy.moxxy_native.AsyncRequestTracker 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 { private fun queryFileName(context: Context, uri: Uri): String {
var result: String? = null var result: String? = null
if (uri.scheme == "content") { 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) val cursor = context.contentResolver.query(uri, null, null, null, null)
cursor.use { cursor -> cursor.use { cursor ->
if (cursor != null && cursor.moveToFirst()) { 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)")
} }
} }
} }