如何将 UIImage 转换为 Swift 中的字节数组 4

How can I convert UIImage to Byte Array In Swift 4

我正在尝试将 UIimage 转换为 swift 中的字节数组。我搜索了很多,但解决方案要么太旧(对于 swift 2),要么不起作用。 有谁知道这样做的方法吗?! 谢谢

试试这个!!

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
}

上面的解决方案不正确,逐字节复制非常慢 一张大图用了 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)