I need an array of pixel data, packed in 8-bit gray-scale format, from a CGImageRef. Here's what I have so far though it seems to be 24-bit RGB:
How do I get an 8-bit gray-scale bitmap from CGImage?
Code:
- (unsigned char *)convertImageToBitmapRep:(NSImage *)image {
CGImageRef imageRef =
[[[NSBitmapImageRep alloc]
initWithData:[image TIFFRepresentation]] CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
void *memory = malloc(width * height);
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceGray();
CGContextRef contextRef = CGBitmapContextCreate(memory,
width,
height,
8,
width,
colorSpaceRef,
kCGImageAlphaNone);
unsigned char *data = (unsigned char *)CGBitmapContextGetData(contextRef);
CGColorSpaceRelease(colorSpaceRef);
CGContextRelease(contextRef);
free(memory);
return data;
}
How do I get an 8-bit gray-scale bitmap from CGImage?