Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Helpful methods for converting to string. #65

Open
FelipeCoro opened this issue Dec 27, 2024 · 1 comment
Open

Helpful methods for converting to string. #65

FelipeCoro opened this issue Dec 27, 2024 · 1 comment

Comments

@FelipeCoro
Copy link

As you know ImageBitmap might not be the best end result for some user in multiplatform, given its not platform independent.
I suggest adding this few lines in the readme, maybe further down the road as a function to help new users obtain a Base64 String they can use to easily store their signature.

commonMain:
expect fun ImageBitmap.toBase64(): String

androidMain:

actual fun ImageBitmap.toBase64(): String {
    val bitmap = this.asAndroidBitmap()
    val byteArrayOutputStream = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)
    val byteArray = byteArrayOutputStream.toByteArray()
    return Base64.encodeToString(byteArray, Base64.NO_WRAP)
}

iosMain:

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

actual fun ImageBitmap.toBase64(): String {
    val uiImage = this.toUIImage()
    val jpegData = uiImage?.let { UIImageJPEGRepresentation(it, 0.5) }
        ?: return ""
    return jpegData.base64Encoding()
}
@joelkanyi
Copy link
Owner

Hey @FelipeCoro , thank you for this! I'll add it to the README and, later, create some utility functions for Sain to convert ImageBitmap to a String across all platforms, including Android, iOS, JVM, WASM, and JS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants