简体   繁体   English

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

[英]How can I convert UIImage to Byte Array In Swift 4

I'm trying to convert an UIimage to byte array in swift .我正在尝试将 UIimage 转换为 swift 中的字节数组。 I've searched a lot but the solutions are either too old ( for swift 2 ) or they don't work .我搜索了很多,但解决方案要么太旧(对于 swift 2)要么不起作用。 Does anyone know a way to do so ?!有没有人知道这样做的方法?! Thanks谢谢

Solution above is incorrect, extremely slow to copy byte per byte It took 4 seconds for a big image, and 0.02s with the following (new constructor from Swift3)上面的解决方案是不正确的,每字节复制一个字节非常慢 大图像需要 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)

Try this!!尝试这个!!

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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