Created
August 26, 2015 13:00
-
-
Save davepkennedy/ab3c9d5739fbe2ee99e1 to your computer and use it in GitHub Desktop.
NSImage <-> CGContextRef
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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