Search code examples
objective-ccimageindexingnsimage

Perplexing indexing bug creating an NSImage from an array of bytes


I'm creating an NSImage from scratch in my code. To start I allocate an array of bytes:

pixels = malloc( (int)( size.width * size.height) * 4 * 8 * sizeof(unsigned char));

I then attempt to create a test image, that should contain a gradient going from pure black on the left to pure red on the right:

-(void)generateTestImage{
    int idx =0;
    for( int i=0; i<(int)(size.height); i++){// Rows
        for (int j=0; j<(int) size.width; j++){// Columns            
            pixels[ idx + 0 ] = 255 * ((float) j / size.width); // r
            pixels[ idx + 1 ] = 0; //  g
            pixels[ idx + 2 ] = 0; //  b
            pixels[ idx + 3 ] = 255;// a

            idx += 4;
        }
    }
}

Finally I convert the array of bytes into a NSImage using:

-(void) convertPixelsToImage{

    if (renderImage == NULL)
        renderImage = [[NSImage alloc] initWithSize:size];
    else{

        NSArray *prevReps = [renderImage representations];
        for (id r in prevReps)
            [renderImage removeRepresentation:r];
    }

    NSLog(@"Creating bitmapImageReprsentation with size:%@", NSStringFromSize(size));
    NSBitmapImageRep *imgRep =
    [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&pixels
                                            pixelsWide:size.width
                                            pixelsHigh:size.height
                                         bitsPerSample:8
                                       samplesPerPixel:sampPerPix
                                              hasAlpha:true
                                              isPlanar:false
                                        colorSpaceName:NSDeviceRGBColorSpace
                                          bitmapFormat:0
                                           bytesPerRow:0
                                          bitsPerPixel:0];

    [renderImage addRepresentation:imgRep];
}

However, the resulting image isn't what I expect.

enter image description here

Here is a zoomed in view of the indexing offset enter image description here

It appears as though my I'm indexing is off, as the gradient pattern shifts by 9 pixels to the left on each row.

Additionally I'm confused by the white stripe at the bottom of the image...

I've spent the last few hours trying various indexing schemes non of which fix the problem. I've verified that I'm using the same size throughout my code. Additionally I've verified that the resulting image has the right dimensions, but its the content that is off.

Is there an obvious problem with this code? Any ideas on how to fix this?


Solution

  • Remember, rows are rounded up to some boundary -- I'm thinking 16 pixels.