Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get underlying NSData from UIImage

I can create UIImage from NSData using [UIImage imageWithData:] or [UIImage initWithData:] methods.

I wonder if I can get the NSData back from an existing UIImage? Something on the line of NSData *myData = [myImage getData];

like image 296
eugene Avatar asked Jan 07 '11 09:01

eugene


2 Answers

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.

like image 194
Caroline Avatar answered Oct 09 '22 03:10

Caroline


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.

like image 20
yesleon Avatar answered Oct 09 '22 04:10

yesleon