2009-08-29 53 views
0

如何在位圖上下文中對每個像素進行迭代?我發現一些似乎試圖做到這一點的來源,但它有點不對。有人能告訴我如何解決這個代碼,以便我可以遍歷每個像素的RGBA?如何在位圖上下文中對每個像素的RGBA進行迭代?

-(UIImage*)modifyPixels:(UIImage*)originalImage 
{ 

NSData* pixelData = (NSData*)CGDataProviderCopyData(CGImageGetDataProvider(originalImage.CGImage)); 
void* pixelBytes = [pixelData bytes]; 

// Take away the red pixel, assuming 32-bit RGBA 
for(int i = 0; i < [pixelData length]; i += 4) { 

     bytes[i] = 0; // red 
     bytes[i+1] = bytes[i+1]; // green 
     bytes[i+2] = bytes[i+2]; // blue 
     bytes[i+3] = bytes[i+3]; // alpha 
    } 

    NSData* newPixelData = [NSData dataWithBytes:pixelBytes length:[pixelData length]]; 
    UIImage* newImage = [UIImage imageWithData:newPixelData]; 

    return newImage; 

}

回答

2

與CGBitmapContextCreate,提供緩衝數據,那麼你的像素將是它。
你可以檢查這link

+0

使用你的緩衝像素是RGBA所以1像素是4字節長,所以與指針緩衝區,你可以走它。 – CiNN 2009-08-29 14:00:57

+0

請教我如何根據上面給出的代碼來做到這一點? – RexOnRoids 2009-08-30 03:37:41

+0

你的新代碼似乎有訣竅,用pixelBytes更改字節並將其轉換爲無符號字符。如果你想訪問一個特定的像素有這個公式(y * width)+ x – CiNN 2009-08-30 10:10:01

相關問題