2011-05-31 94 views
1

我操纵像素来打开灰度,除了在图像的底部,我都有蓝色的像素。这看起来越多,图像的尺寸就越小,并在某个点之后消失。任何人都可以看到我做错了什么?问题CoreGraphics像素操作蓝色

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

+0

规则#0:不抛弃常量:'无符号字符* RAWDATA =(无符号字符*)CFDataGetBytePtr(dataref);' – justin 2011-06-01 03:28:09

回答

1

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

NSUInteger length = CFDataGetLength(dataref); 
1

还有一个原因,没有人回答了 - 张贴在你的问题的代码似乎绝对精品!

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

唯一不同于你的问题的是CopyPixelData和钳位功能 - 也许你的问题在于这些?

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

山姆

+0

感谢这个,但是实际上我在刚才提到的问题一个答案。 – David 2011-06-01 04:04:39

+0

啊,这很有趣 - 我不知道有时会给出奇怪的答案:) – deanWombourne 2011-06-01 12:05:50