Q:

Convert UIImage to byte array in swift

How can I convert a UIimage into a Byte Array, so I can upload it into my web service?

A:

You can actually use a couple of lines to do it
guard let image = UIImage(named: "someImage") else { return }
guard let data = image?.jpegData(compressionQuality: 1.0) else { return }
// OR
guard let data = image?.pngData() else { return }

The number should range from 0.0 to 1.0 and sets the jpeg quality. PNG is lossless so there is no need for compression quality identifier but be aware that the file size can be about 10 times higher
--- update ---
Updated for Swift 5.1

A:

You can convert UIImage to NSData and pass it to this method
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

}

