Skip to content

Instantly share code, notes, and snippets.

@hasanadil
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasanadil/8481ec96f3593f94cce6 to your computer and use it in GitHub Desktop.
Save hasanadil/8481ec96f3593f94cce6 to your computer and use it in GitHub Desktop.
-(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