saad
saad

Reputation: 1245

32 bit Grayscale Image with CGBitmapContextCreate always Black

I'm using the following code to display a 32 bit Grayscale image. Even if I explicitly set every pixel to be 4294967297 (which ought to be white), the end result is always black. What am I doing wrong here? The image is just 64x64 pixels.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
ptr = (float*)malloc(4*xDim*yDim);
for(i=0;i<yDim;i++)
{
    for(j=0;j<xDim;j++)
    {
        ptr[i*xDim + j] = 4294967297;
    }
}
CGContextRef bitmapContext = CGBitmapContextCreate(
                                                   ptr,
                                                   xDim,
                                                   yDim,
                                                   32,
                                                   4*xDim,
                                                   colorSpace,
                                                   kCGImageAlphaNone | kCGBitmapFloatComponents);

//ptr = CGBitmapContextGetData(bitmapContext);


//NSLog(@"%ld",sizeof(float));

CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);

NSRect drawRect;
drawRect.origin = NSMakePoint(1.0, 1.0);
drawRect.size.width = 64;
drawRect.size.height = 64;
NSImage *greyscale = [[NSImage alloc] initWithCGImage:cgImage size:NSZeroSize];
[greyscale drawInRect:drawRect
             fromRect:NSZeroRect
            operation:NSCompositeSourceOver
             fraction:1.0];

Upvotes: 1

Views: 1741

Answers (4)

T.J.
T.J.

Reputation: 3960

32 bit floating point gray scale is not supported by CGBitmapContextCreate. CGBitmapContextCreate Supported Color Spaces

Upvotes: 0

koan
koan

Reputation: 3686

Are you showing the exact code you are using ?

2^32 - 1 = 4294967295

If you are using 4294967297 I suspect you are getting overflow and an actual value of 2 !

Upvotes: 0

Demitri
Demitri

Reputation: 14039

If you don't specify the endianness, Quartz will default to big-endian. If you are on an Intel Mac, this will be wrong. You will need to explicitly set the endianness, and the best way to do that is to change your flags to:

kCGImageAlphaNone | kCGBitmapFloatComponents | kCGBitmapByteOrder32Host

This will work properly regardless of your CPU (for future compatibility!). You can find more detail here: http://lists.apple.com/archives/Quartz-dev/2011/Dec/msg00001.html

Upvotes: 1

Alexander B
Alexander B

Reputation: 407

You are using a float component image. Make sure ptr has type float* and try setting values to 0.5f instead of 4294967297.

Upvotes: 0

Related Questions