https://kotlinlang.org logo
Title
j

Justin Xu

05/13/2023, 8:38 PM
I am trying to center crop a
UIImage
in iOS and convert the cropped version to a
ByteArray
to send through HTTP, is this correct?
val croppedUIImage = bitmap.image.CGImage?.let { cgImage ->
    val width = CGImageGetWidth(cgImage).toDouble()
    val height = CGImageGetHeight(cgImage).toDouble()

    val squareSize = minOf(width, height)
    val x = (width - squareSize) / 2
    val y = (height - squareSize) / 2

    val rect = CGRectMake(x, y, squareSize, squareSize)

    UIImage(CGImageCreateWithImageInRect(image = cgImage, rect = rect))
} ?: throw NullPointerException("Null CGImage")

val nsData = UIImagePNGRepresentation(croppedUIImage)
    ?: throw CharacterCodingException("Can't represent UIImage as PNG")

return ByteArray(nsData.length.toInt()).apply {
    usePinned {
        memcpy(it.addressOf(0), nsData.bytes, nsData.length)
    }
}
When I send this as
image/png
, I get a "Bad Content-Type format: text; charset=utf-8" error
a

ayodele

05/14/2023, 9:44 PM
Are you sending it using Ktor??
j

Justin Xu

05/14/2023, 10:00 PM
Yes, attaching byte array as body
a

ayodele

05/15/2023, 6:29 AM
I think your content type is wrong.
Check the API you are uploading to. When uploading to Google drive we use
ContentType.Multipart.FormData
Anything else, we get a bad content type error
j

Justin Xu

05/15/2023, 8:13 AM
Well yes, the error is telling me the content type is wrong. I'm trying to figure out if it's an issue with the way I'm generating the
ByteArray
in iOS, since the process of image -> bytearray -> send through HTTP works in Android. For context, I am uploading to AWS API Gateway, and sending the image file as binary data through Ktor as
image/png
has been working fine for me
a

ayodele

05/15/2023, 8:47 AM
Okay. Your code to convert nsdata to
ByteArray
is correct. That's what we use currently. Maybe you should try to save the result of the cropped image. I guess you tried that