5

What is the best way to save CGImageRef to a png or jpeg file in iOS?

For a general cocoa application (not using UIkit), see: Saving CGImageRef to a png file? but this seems too long and clunky.

Community
  • 1
  • 1
Guy
  • 12,250
  • 6
  • 53
  • 70

1 Answers1

5

Using UIKit, the code becomes a simple 3-liner:

UIImage *uiImage = [UIImage imageWithCGImage:cgImage];
NSData *jpgData = UIImageJPEGRepresentation(uiImage, 0.9f);
[jpgData writeToFile:path atomically:NO];
Guy
  • 12,250
  • 6
  • 53
  • 70
  • 1
    @trojanfoe on StackOverflow it is not merely OK to ask and answer your own question, it is explicitly encouraged. see: http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ – Guy Feb 12 '13 at 11:26
  • 1
    I stand corrected. What have I been missing all these years? – trojanfoe Feb 12 '13 at 11:27
  • However won't the image be upside down? http://stackoverflow.com/questions/3632702/flip-the-image-when-saving-out-to-disk – trojanfoe Feb 12 '13 at 11:31
  • As an aside, in general, I'd suggest PNG format rather than JPG. You get transparencies and lossless compression. – Rob Feb 12 '13 at 11:38
  • @Rob thanks. I am aware of that, and needed JPEG specifically. – Guy Feb 12 '13 at 12:28