8

I have drawn into a CGContext of a UIView.

- (void)drawRect:(CGRect)rect { 
    [self drawInContext:UIGraphicsGetCurrentContext()]  
}

I would like to save what I have drawn to a png file.

Is there a simple solution?

EDIT: Based on suggestions below - here's what I have so far....

-(void)createImage {
    NSString* outFile = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/image.png"];
    DLog(@"creating image file at %@", outFile);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:outFile 
                atomically:NO];
}

- (void)drawRect:(CGRect)rect { 
    [self drawInContext:UIGraphicsGetCurrentContext()]; 
    [self createImage];
}
sylvanaar
  • 8,096
  • 37
  • 59

4 Answers4

6
CGImageRef imgRef = CGBitmapContextCreateImage(context);

UIImage* img = [UIImage imageWithCGImage:imgRef];

CGImageRelease(imgRef);
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
Prashanth Rajagopalan
  • 718
  • 1
  • 10
  • 27
  • 1
    Don't just post code as an answer, try to give it some explanation as to why this will help. – Dutts Feb 22 '13 at 09:19
6
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:@"image.png"];
indragie
  • 18,002
  • 16
  • 95
  • 164
  • I must be missing something simple. I do this within the drawRect call. Running on the iPhone simulator - i don't see any file created. – sylvanaar Apr 02 '10 at 19:33
  • You may have to specify the complete path to the Documents directory instead of just image.png. – indragie Apr 02 '10 at 20:59
  • I updated my example code above - but no file is created in the emulator. Thanks for the help though. – sylvanaar Apr 03 '10 at 04:44
1

Call UIGraphicsGetImageFromCurrentImageContext to get an UIImage.
Then call UIImagePNGRepresentation to get an NSData of the UIImage encoded in PNG.
Finally, call -writeToFile:… to save the NSData.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
0
let imageWidth = inputCGImage.width
let imageHeight = inputCGImage.height

let imageRect = NSRect(
    origin: .zero,
    size: CGSize(width: imageWidth, height: imageHeight)
)

context.draw(inputCGImage, in: imageRect)

let outputImageRef = context.makeImage()!

let paths = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true) as [String]

let destinationURL = NSURL(fileURLWithPath: paths.first!).appendingPathComponent("output.png")!

guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypePNG, 1, nil) else {
    throw HoleFillingError.CoreGraphicsError
}

CGImageDestinationAddImage(destination, outputImageRef, nil)
CGImageDestinationFinalize(destination)
Eric
  • 16,003
  • 15
  • 87
  • 139