cocoa-touchuiimagensdata

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];


Solution

  • Objective-C

    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.

    Swift

    In modern versions of Swift, the methods above have been replaced with

    let data = image.jpegData(compressionQuality: 0.7)
    

    and

    let data = image.pngData()
    

    respectively.

    Note that both return an optional value (Data?).