在swift中将UIImage转换为字节数组
如何将UIimage转换为字节数组,以便将其上传到我的Web服务中?
您实际上可以使用一行来完成它
guard let image = UIImage(named: "someImage") else { return } // BAIL let data = UIImageJPEGRepresentation(image, 1.0)
数字应在0.0到1.0之间,并设置jpeg质量
--- update ---
从Swift 3.1开始仍然有效
您可以将UIImage
转换为NSData
并将其传递给此方法
func getArrayOfBytesFromImage(imageData:NSData) -> NSMutableArray { // the number of elements: let count = imageData.length / sizeof(UInt8) // create array of appropriate length: var bytes = [UInt8](count: count, repeatedValue: 0) // copy bytes into array imageData.getBytes(&bytes, length:count * sizeof(UInt8)) var byteArray:NSMutableArray = NSMutableArray() for (var i = 0; i < count; i++) { byteArray.addObject(NSNumber(unsignedChar: bytes[i])) } return byteArray }