8-bit gray-scale bitmap from CGImage

Discussion in 'Mac Programming' started by mqt, Nov 27, 2008.

  1. mqt macrumors newbie

    Joined:
    Jul 12, 2008
    #1
    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:

    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?
     
  2. Sayer macrumors 6502a

    Sayer

    Joined:
    Jan 4, 2002
    Location:
    Austin, TX
    #2

Share This Page