Search code examples
iphoneipadcore-graphicsquartz-graphics

How can I save a Bitmap Image, represented by a CGContextRef, to the iPhone's hard drive?


I have a little sketch program that I've managed to throw together using Quartz2D, but I'm very new to the iOS platform and I'm having trouble figuring out how to allow the user to save their sketch. I have a CGContextRef that contains the sketch, how can I save it so that it can later be retrieved? Once it's saved, how can I retrieve it?

Thanks so much in advance for your help! I'm going to continue reading up on this now...


Solution

  • Here's how I did it...

    Saving

    CGImageRef imageRef = CGBitmapContextCreateImage(bitmapContext);
    UIImage* image = [[UIImage alloc] initWithCGImage:imageRef];
    NSData* imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:filePath atomically:YES];
    

    Retrieving

    UIImage* image = [UIImage imageWithContentsOfFile:filePath];
    CGImageRef imageRef = [image CGImage];