CoreGraphics Pixel Manipulation Blue

时间:2011-05-31 14:10:57

标签: iphone objective-c core-graphics pixel

我正在操纵像素来转动灰度,并且一切都很好看,除了在图像的底部我有蓝色像素。这看起来越多,图像的尺寸越小,并且在某一点之后消失。谁能看到我做错了什么?

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);

问题示例:http://iforce.co.nz/i/3rei1wba.utm.jpg

2 个答案:

答案 0 :(得分:1)

有一个原因是没有人回答 - 你问题中贴出的代码似乎绝对没问题!

我在这里做了一个测试项目:https://github.com/oneblacksock/stack_overflow_answer_6188863当我用你的代码运行它时,它完美无缺!

与您的问题不同的唯一一点是CopyPixelData和钳位功能 - 也许您的问题出现在这些中?

下载我的测试项目,看看我做了什么 - 尝试使用你知道的图像,让我知道你是怎么做的!

萨姆

答案 1 :(得分:1)

问题是我假设CGImageGetWidth(imageRef) == CGImageGetBytesPerRow(imageRef) - 情况并非总是如此。在Apple开发者论坛上向我指出这是正确的。我已经改为使用dataref的长度,现在它按预期工作。

NSUInteger length = CFDataGetLength(dataref);
相关问题