简体   繁体   中英

How can I change UIimage to binary data in Swift

I want to send Image data(capture a snapshot) to Python server by decoding information to byte(UInt8) array but did't well :(

My code is here

typealias Byte = UInt8

let captureImage:UIImage = self.sceneView.snapshot()

//change UIImage to binary data

let imageData: NSData = UIImageJPEGRepresentation(captureImage, 0)! as NSData

let AR_IMG_WIDTH = Int(captureImage.size.width) //750
let AR_IMG_HEIGHT = Int(captureImage.size.height) //1334
let AR_BUFFER_SIZE = AR_IMG_WIDTH * AR_IMG_HEIGHT * 3 + 6 //3001506 , 3(R,G,B),6 (MMS+MME)

print("size of imageData 750 * 1334 * 3 : \(imageData.length)")

//NSData to [Byte]
var mms: [Byte] = [Byte]("MMS".utf8) // 3Byte
let mme: [Byte] = [Byte]("MME".utf8) // 3Byte
var copyArray = [Byte](repeating: 0, count: imageData.length)
imageData.getBytes(&copyArray, length: imageData.length)
mms.append(contentsOf: copyArray)
mms.append(contentsOf: mme)

My question is this

1) Why imageData.length(size of byte) value is mutable? I tought this value must be ImageWidth * ImageHeight * 3(R,G,B data) + 6 (MMS, MME) byte

2) If i want to transfer the image information, use another function or class?

Let me answer your question 1)

JPEG, like many other image formats, compresses the RGB image data. This means that the number of bytes is not a bit more than width X height X 3, but much less.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM