Skip to content

Commit

Permalink
workaround for android file picker image conversion issue
Browse files Browse the repository at this point in the history
  • Loading branch information
joreilly committed Jan 20, 2024
1 parent 702a799 commit c5ec3e4
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/android.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Android CI

on: pull_request

jobs:
build:

runs-on: macos-latest

steps:
- uses: actions/checkout@v4
- name: set up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'zulu'
java-version: 17
- name: Build android app
run: ./gradlew assembleDebug
- name: Run Unit Tests
run: ./gradlew test
- name: Build iOS shared code
run: ./gradlew :composeApp:compileKotlinIosSimulatorArm64

27 changes: 23 additions & 4 deletions composeApp/src/androidMain/kotlin/actual.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import android.content.ContentResolver
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import com.darkrockstudios.libraries.mpfilepicker.FilePicker
import com.darkrockstudios.libraries.mpfilepicker.MPFile
import com.mikepenz.markdown.m3.Markdown
import kotlinx.coroutines.launch
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi


actual fun ByteArray.toComposeImageBitmap(): ImageBitmap {
return BitmapFactory.decodeByteArray(this, 0, size).asImageBitmap()
}
Expand All @@ -29,15 +34,29 @@ actual fun ImagePicker(
onImageSelected: ImageFileImported,
) {
val coroutineScope = rememberCoroutineScope()
val contentResolver = LocalContext.current.contentResolver

val fileExtensions = listOf("jpg", "png")
FilePicker(show = show, fileExtensions = fileExtensions) { file ->
coroutineScope.launch {
val data = file?.getFileByteArray()
data?.let {
val base64EncodedImageData = Base64.encode(data)
onImageSelected(file.path, base64EncodedImageData)
file?.let {
val data = getImageByteArray(file, contentResolver)
data?.let {
val base64EncodedImageData = Base64.encode(data)
onImageSelected(file.path, base64EncodedImageData)
}
}
}
}
}


fun getImageByteArray(file: MPFile<Any>, contentResolver: ContentResolver): ByteArray? {
val uri = Uri.parse(file.path)
val stream = contentResolver.openInputStream(uri)
stream?.let {
val bytes = stream.readBytes()
stream.close()
return bytes
} ?: return null
}

0 comments on commit c5ec3e4

Please sign in to comment.