Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Created August 26, 2015 13:00
Show Gist options
  • Select an option

  • Save davepkennedy/ab3c9d5739fbe2ee99e1 to your computer and use it in GitHub Desktop.

Select an option

Save davepkennedy/ab3c9d5739fbe2ee99e1 to your computer and use it in GitHub Desktop.
NSImage <-> CGContextRef
CGContextRef fromImage(NSImage* image)
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSSize size = [image size];
CGContextRef contextRef = CGBitmapContextCreate(NULL, size.width, size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
NSGraphicsContext *graphicsContext = [NSGraphicsContext graphicsContextWithCGContext:contextRef flipped:NO];
NSGraphicsContext* currentContext = [NSGraphicsContext currentContext];
[NSGraphicsContext setCurrentContext:graphicsContext];
[image drawInRect:NSMakeRect(0, 0, size.width, size.height)];
[NSGraphicsContext setCurrentContext:currentContext];
CGColorSpaceRelease(colorSpace);
return contextRef;
}
NSImage* fromContext (CGContextRef context)
{
CGImageRef imageRef = CGBitmapContextCreateImage(context);
NSImage* newImage = [[NSImage alloc] initWithCGImage:imageRef
size:NSMakeSize(
CGBitmapContextGetWidth(context),
CGBitmapContextGetHeight(context))];
return newImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment