How can I get a `ByteArray` from `UIImage`?
# ios
e
How can I get a
ByteArray
from
UIImage
?
r
In Swift or Kotlin? This works for me in Swift:
Copy code
extension UIImage {
    func toByteArray() -> KotlinByteArray? {
        if let data = self.resize(targetSize: CGSizeMake(1020, 768)).jpegData(compressionQuality: 0.8) {
            return ImageUtils().dataToByteArray(data: data)
        } else {
            return nil
        }
    }
}
I haven't tried it in Kotlin, but that might give you some clues at least.
e
@Russell Stewart I don’t see
resize
method in UIImage
and what is ImageUtils?
I am trying to do that in Kotlin
r
Ah! Sorry, my mistake.
ImageUtils
is a shared object I wrote in the ios Kotlin module:
Copy code
typealias ImageBytes = NSData
@OptIn(ExperimentalForeignApi::class)
fun ImageBytes.toByteArray(): ByteArray = ByteArray(this@toByteArray.length.toInt()).apply {
    usePinned {
        memcpy(it.addressOf(0), this@toByteArray.bytes, this@toByteArray.length)
    }
}

@Suppress("unused")
object ImageUtils {
    fun dataToByteArray(data: NSData): ByteArray {
        return data.toByteArray()
    }
}
I'm not sure why you aren't seeing the
resize
method in
UIImage
though.
Although that's not relevant to your question anyway. I just have that to resize the image for faster upload; it's not necessary for converting to a
ByteArray
.
289 Views