Last active
August 29, 2015 14:27
-
-
Save hasanadil/8481ec96f3593f94cce6 to your computer and use it in GitHub Desktop.
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
-(void) pixelsFromImage:(NSImage*)image | |
withCompletion:(void(^)(UInt32 *pixels, NSUInteger pixelCount))completion { | |
//Extract pixels from the image in a 1D array | |
CFDataRef inputData = (__bridge CFDataRef)[image TIFFRepresentation]; | |
CGImageSourceRef inputSource = CGImageSourceCreateWithData(inputData, NULL); | |
CGImageRef inputCGImage = CGImageSourceCreateImageAtIndex(inputSource, 0, NULL); | |
NSUInteger width = CGImageGetWidth(inputCGImage); | |
NSUInteger height = CGImageGetHeight(inputCGImage); | |
NSUInteger numberOfPixels = height * width; | |
NSUInteger bytesPerPixel = 4; | |
NSUInteger bytesPerRow = bytesPerPixel * width; | |
NSUInteger bitsPerComponent = 8; | |
//Store all pixels in this array | |
UInt32 * pixels; | |
pixels = (UInt32 *) calloc(numberOfPixels, sizeof(UInt32)); | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); | |
CGContextRef context = CGBitmapContextCreate(pixels, width, height, | |
bitsPerComponent, bytesPerRow, | |
colorSpace, | |
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); | |
//Fill in the pixels array | |
CGContextDrawImage(context, CGRectMake(0, 0, width, height), inputCGImage); | |
//Cleanup | |
CGColorSpaceRelease(colorSpace); | |
CGContextRelease(context); | |
if (completion) { | |
completion(pixels, numberOfPixels); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment