views:

464

answers:

1

How do I iterate on EACH PIXEL in a bitmap context? I found some source that seems to be attempting to do this but it is somehow flawed. Can someone tell me how to fix this code so that I can iterate on the RGBA of each pixel?

-(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  A: 

with CGBitmapContextCreate, provide a buffer for data, then your pixels will be in it.
You can check this link

CiNN
using you buffer the pixels are RGBA so 1 pixel is 4 bytes long so with the pointer to your buffer you can walk it.
CiNN
Would you please teach me how to do this based on the given code above?
RexOnRoids
your new code seems to do the trick, change bytes with pixelBytes and cast it as a unsigned char. If you want to access a specific pixel there is this formula ( y * width ) + x
CiNN
Thanks CiNN, this helped.
RexOnRoids
CiNN-how do i use this formula:-( y * width ) + x can you provide a sample to modify pixels of a bitmap image
Rahul Vyas