2011-05-31 87 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