Skip to content

Commit 4764a6f

Browse files
fix: load base64 image on android (#240)
* fix: load base64 image on android * fix: handle base64 string before coil img
1 parent 9878efa commit 4764a6f

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

android/src/main/java/com/jimmydaddy/imagemarker/MarkerImageLoader.kt

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import android.graphics.Bitmap
66
import android.graphics.BitmapFactory
77
import android.os.Build
88
import android.os.Build.VERSION.SDK_INT
9+
import android.util.Base64
910
import android.util.Log
1011
import androidx.annotation.RequiresApi
1112
import androidx.core.graphics.drawable.toBitmap
@@ -48,9 +49,22 @@ class MarkerImageLoader(private val context: ReactApplicationContext, private va
4849
val deferredList = images.map { img ->
4950
async {
5051
try {
52+
5153
val isCoilImg = isCoilImg(img.uri)
5254
Log.d(IMAGE_MARKER_TAG, "isCoilImg: $isCoilImg")
53-
if (isCoilImg) {
55+
56+
if (isBase64String(img.uri)) {
57+
Log.d(IMAGE_MARKER_TAG, "Loading Base64 Image")
58+
decodeBase64ToBitmap(img.uri)?.let { bitmap ->
59+
val scaledBitmap = ImageProcess.scaleBitmap(bitmap, img.scale)
60+
?: throw MarkerError(ErrorCode.LOAD_IMAGE_FAILED, "Failed to scale Base64 image")
61+
if (!bitmap.isRecycled && img.scale != 1f) {
62+
bitmap.recycle()
63+
System.gc()
64+
}
65+
return@async scaledBitmap
66+
} ?: throw MarkerError(ErrorCode.GET_RESOURCE_FAILED, "Failed to decode Base64 image")
67+
} else if (isCoilImg) {
5468
val future = CompletableFuture<Bitmap?>()
5569
var request = ImageRequest.Builder(context)
5670
.data(img.uri)
@@ -130,4 +144,20 @@ class MarkerImageLoader(private val context: ReactApplicationContext, private va
130144
)
131145
}
132146

147+
148+
private fun isBase64String(s: String?): Boolean {
149+
if (s == null) return false
150+
return s.startsWith("data:image/") && s.contains(";base64,")
151+
}
152+
153+
private fun decodeBase64ToBitmap(base64Str: String?): Bitmap? {
154+
if (base64Str == null) return null
155+
return try {
156+
val imageBytes = Base64.decode(base64Str.substring(base64Str.indexOf(",") + 1), Base64.DEFAULT)
157+
BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
158+
} catch (e: Exception) {
159+
Log.e("ImageLoader", "Failed to decode Base64 image", e)
160+
null
161+
}
162+
}
133163
}

0 commit comments

Comments
 (0)