Reputation: 31
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
Upvotes: 1
Views: 511
Reputation: 31
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);
Upvotes: 1
Reputation: 38475
There's a reason that no-one has answered - the code posted in your question seems absolutely fine!
I've made a test project here : https://github.com/oneblacksock/stack_overflow_answer_6188863 and when I run it with your code in, it works perfectly!
The only bits that are different from your problem are the CopyPixelData and the clamp functions - perhaps your problem is in these?
Download my test project and see what I've done - try it with an image you know is broken and let me know how you get on!
Sam
Upvotes: 1