iphoneobjective-ccore-graphicspixel

CoreGraphics Pixel Manipulation Blue


I'm manipulating pixels to turn the greyscale and all appears well, except at the bottom of the image I have blue colored pixels. This appears more the smaller in dimensions the image is and disappears after a certain point. Can anyone see what I'm doing wrong?

CGImageRef imageRef = image.CGImage;

NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CFDataRef dataref = CopyImagePixels(imageRef);

unsigned char *rawData = (unsigned char *)CFDataGetBytePtr(dataref);

int byteIndex = 0;

for (int ii = 0 ; ii < width * height ; ++ii)

{

   int red = (int)rawData[byteIndex];
   int blue = (int)rawData[byteIndex+1]; 
   int green = (int)rawData[byteIndex+2];

   int r, g, b;

   r = (int)(red * 0.30) + (green * 0.59) + (blue * 0.11);
   g = (int)(red * 0.30) + (green * 0.59) + (blue * 0.11);
   b = (int)(red * 0.30) + (green * 0.59) + (blue * 0.11);


   rawData[byteIndex] = clamp(r, 0, 255);
   rawData[byteIndex+1] = clamp(g, 0, 255);
   rawData[byteIndex+2] = clamp(b, 0, 255);
   rawData[byteIndex+3] = 255;

   byteIndex += 4;

}



CGContextRef ctx = CGBitmapContextCreate(rawData,
                                        CGImageGetWidth(imageRef),
                                        CGImageGetHeight(imageRef),
                                        CGImageGetBitsPerComponent(imageRef),
                                        CGImageGetBytesPerRow(imageRef),
                                        CGImageGetColorSpace(imageRef),
                                        kCGImageAlphaPremultipliedLast); 


imageRef = CGBitmapContextCreateImage (ctx);
CFRelease(dataref);
UIImage* rawImage = [UIImage imageWithCGImage:imageRef];  
CGImageRelease(imageRef);
CGContextRelease(ctx);

Example of problem: http://iforce.co.nz/i/3rei1wba.utm.jpg


Solution

  • The problem is I am assuming CGImageGetWidth(imageRef) == CGImageGetBytesPerRow(imageRef) - which isn't always the case. This was pointed out to me on the Apple developer forums and is correct. I've changed to use the length of the dataref and now it works as expected.

    NSUInteger length = CFDataGetLength(dataref);