简体   繁体   中英

How can I convert UIImage to Byte Array In Swift 4

I'm trying to convert an UIimage to byte array in swift . I've searched a lot but the solutions are either too old ( for swift 2 ) or they don't work . 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)

 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
}

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