Has anyone written the code to save an `ImageBitma...
# compose-ios
a
Has anyone written the code to save an
ImageBitmap
to the photos library on iOS via Kotlin? I'm looking around for a code sample but can't quite find it. I have some code but I get an odd null pointer exception:
Copy code
actual fun saveBitmap(bmp: ImageBitmap) {
        PHPhotoLibrary.requestAuthorization { status ->
            if (status == PHAuthorizationStatusAuthorized) {
                PHPhotoLibrary.sharedPhotoLibrary().performChanges({

                    val bytes = bmp.asSkiaBitmap().readPixels()

                    bytes?.let { array ->
                        val nsData = array.toNSData()

                        val img = UIImage(data = nsData)

                        PHAssetChangeRequest.creationRequestForAssetFromImage(img)
                    }
                }, null)
            }
        }
    }
1
Update: I'm fairly certain the crash is happening when I'm trying to create the UIImage; I think I need to massage the pixel data but I'm unsure quite how to do that
a
Just guessing here, but what formats does UIImage expects to get? What you’re giving it is a raw array of pixels, but what it probably expects is JPEG/PNG data.
a
Yeah that's what I need to find out
The
NSData
bytearray probably has to probably be just so
a
Maybe try
Image.makeFromBitmap(bmp.asSkiaBitmap()).encodeToData().bytes
thank you color 1
a
I can do that!
a
That should give you a PNG
encodeToData
takes a format argument if you want other formats
a
That did the trick!
Solution: this is the save method that works:
Copy code
actual fun saveBitmap(bmp: ImageBitmap) {
        PHPhotoLibrary.requestAuthorization { status ->
            if (status == PHAuthorizationStatusAuthorized) {
                PHPhotoLibrary.sharedPhotoLibrary().performChanges({
                    val bytes = Image.makeFromBitmap(bmp.asSkiaBitmap()).encodeToData()!!.bytes
                    val nsData = bytes.toNSData()

                    val img = UIImage(data = nsData)
                    PHAssetChangeRequest.creationRequestForAssetFromImage(img)
                }, null)
            }
        }
    }
Thanks so much @Alexander Maryanovsky
d