i'm having trouble converting a skiko Bitmap to an...
# multiplatform
n
i'm having trouble converting a skiko Bitmap to an NSImage. wondering if anyone has got this working. here's what i've tried; but it throws an NPE:
Copy code
val nsImage = bitmap.readPixels()?.let { pixels ->
    NSImage(data = pixels.usePinned {
        NSData.create(it.addressOf(0), pixels.size.convert())
    })
}
i've also only found this helper for NSData -> skiko Image. nothing for the other direction: https://github.com/JetBrains/skiko/blob/master/skiko/src/darwinMain/kotlin/org/jetbrains/skia/Image.darwin.kt Slack Conversation
b
It might be because the Kotlin bitmap is not in the same format as the NSImage, so when you do a direct copy of bytes it doesn't work out. Try encoding the bitmap to a standard format, like PNG or JPEG and then creating the NSImage when you know the format. Here is the code I just write for encoding an ImageBitmap:
Copy code
// Common
expect fun ImageBitmap.encodeToBytes(encoding: BitmapEncoding, quality: Int = 100): ByteArray?
Copy code
// Android

import android.graphics.Bitmap
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asAndroidBitmap
import java.io.ByteArrayOutputStream

actual fun ImageBitmap.encodeToBytes(
    encoding: BitmapEncoding,
    quality: Int,
): ByteArray? {
    ByteArrayOutputStream().use { bytes ->
        this.asAndroidBitmap().compress(
            when (encoding) {
                BitmapEncoding.JPEG -> {
                    Bitmap.CompressFormat.JPEG
                }

                BitmapEncoding.PNG -> {
                    Bitmap.CompressFormat.PNG
                }
            }, quality, bytes
        )

        return bytes.toByteArray()
    }
}
Copy code
// Native
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asSkiaBitmap
import org.jetbrains.skia.Image

actual fun ImageBitmap.encodeToBytes(
    encoding: BitmapEncoding,
    quality: Int,
): ByteArray? {
    return Image.makeFromBitmap(this.asSkiaBitmap())
        .encodeToData(
            when (encoding) {
                BitmapEncoding.JPEG -> {
                    org.jetbrains.skia.EncodedImageFormat.JPEG
                }

                BitmapEncoding.PNG -> {
                    org.jetbrains.skia.EncodedImageFormat.PNG
                }
            }, quality
        )?.bytes
}
You should then be able to take those bytes and create an NSData with them.
n
this worked! thank you for the quick help on this.
👍 1