Get underlying NSData from UIImage

Swift 4.2

let dataPng = image.pngData() // return image as PNG. May return nil if image has no CGImageRef or invalid bitmap format

let dataJpg = image.jpegData(compressionQuality: 1) // return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compression is 0(most)..1(least)

NSData *imageData = UIImageJPEGRepresentation(image, 0.7); // 0.7 is JPG quality

or

NSData *imageData = UIImagePNGRepresentation(image);

Depending if you want your data in PNG format or JPG format.


When initialising a UIImage object with init(data: originalData), that originalData will be converted into raw data in some kind of internal format. These data can be retrieved later with

let rawData = myImage.cgImage?.dataProvider?.data as Data?

However because the rawData is raw, it is going to be even larger than when using UIImagePNGRepresentation.