我正在尝试将UIimage迅速转换为字节数组。我搜索了很多,但是解决方案太旧(快速2)或无法使用。 有人知道这样做的方法吗? 谢谢
答案 0 :(得分:0)
尝试一下!
guard let image = UIImage(named: "someImage") else { return }
let data = UIImageJPEGRepresentation(image, 1.0)
OR you can convert UIImage to NSData
func getArrayOfBytesFromImage(imageData:NSData) -> NSMutableArray
{
// the number of elements:
let count = data.length / MemoryLayout<UInt8>.size
// create array of appropriate length:
var bytes = [UInt8](repeating: 0, count: count)
// copy bytes into array
imageData.getBytes(&bytes, length:count)
var byteArray:NSMutableArray = NSMutableArray()
for (var i = 0; i < count; i++) {
byteArray.addObject(NSNumber(unsignedChar: bytes[i]))
}
return byteArray
}
答案 1 :(得分:0)
上述解决方案不正确,每个字节复制字节的速度非常慢 一张大图片花了4秒,以下花了0.02秒(Swift3的新构造函数)
let data: [UInt8] = [...]
let image = UIImage(data: Data(bytes: data, count: data.count))
guard let dataPng: Data = image.pngData() else { return [] }
let finalData = [UInt8](dataPng)