hafiz
08/05/2024, 5:47 AMexpect fun ImageBitmap.toBase64():String
step 2: implement function here in both side android (androidMain) and ios (iosMain)
actual fun ImageBitmap.toBase64(): String { // folder androidMain
val bitmap: Bitmap = this.asAndroidBitmap()
val byteArrayOutputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream)
val byteArray = byteArrayOutputStream.toByteArray()
return Base64.encodeToString(byteArray, Base64.DEFAULT)
}
actual fun ImageBitmap.toBase64(): String { // folder iosMain
val uiImage = this.toUIImage()
val jpegData = uiImage?.let { UIImageJPEGRepresentation(it, 0.5) } ?: return "" // Adjust compression quality here (0.0 to 1.0)
val base64String = jpegData.base64EncodedStringWithOptions(0u)
return base64String
}
@OptIn(ExperimentalForeignApi::class)
fun ImageBitmap.toUIImage(): UIImage? {
val width = this.width
val height = this.height
val buffer = IntArray(width * height)
this.readPixels(buffer)
val colorSpace = CGColorSpaceCreateDeviceRGB()
val context = CGBitmapContextCreate(
data = buffer.refTo(0),
width = width.toULong(),
height = height.toULong(),
bitsPerComponent = 8u,
bytesPerRow = (4 * width).toULong(),
space = colorSpace,
bitmapInfo = CGImageAlphaInfo.kCGImageAlphaPremultipliedLast.value
)
val cgImage = CGBitmapContextCreateImage(context)
return cgImage?.let { UIImage.imageWithCGImage(it) }
}
step3: set api send data here :
@Serializable
data class ProfilePictureRequestUpdate(val encodeStringImage:String)
calling api
client.put{
val fileName = "sample_image_${Clock.System.now()}"
url (queryUrl + pathProfileUpdate)
setBody( MultiPartFormDataContent(
formData {
append(
key = keyUpload,
value = profilePicture.encodeStringImage,
headers = Headers.build {
append(HttpHeaders.ContentType, "image/jpg")
append(HttpHeaders.ContentDisposition, "filename=\"$fileName.jpg\"")
}
)
}
)
)
onUpload { bytesSentTotal, contentLength ->
Napier.d { "Sent $bytesSentTotal bytes from $contentLength" }
}
}.body()
That's all, I hope benefit for all of us here who looking for upload the image.hafiz
08/05/2024, 5:50 AMStefan Oltmann
08/05/2024, 7:48 AMhafiz
08/06/2024, 1:59 AMStefan Oltmann
08/06/2024, 5:23 AMhafiz
08/06/2024, 6:54 AMStefan Oltmann
08/06/2024, 6:54 AMChrimaeon
08/06/2024, 8:51 AMapplication/octet-stream
hafiz
08/07/2024, 1:02 AMChrimaeon
08/07/2024, 6:51 AMhafiz
08/09/2024, 11:03 PM