Can I edit the pixels of the UIImage’s property CGImage

You cannot get at the original pixels. However, you can get a copy. One option is to do what Matt suggested, and convert it into a PNG/JPG – though remember, the image is now compressed, and you will be manipulating the compressed file and not the pixels directly.

If you want to get at a copy of the raw pixels, you can do something like:

UIImage* image = ...; // An image
NSData* pixelData = (NSData*) CGDataProviderCopyData(CGImageGetDataProvider(image.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
}

Now, if you wanted to make this into a new UIImage, you can do something like:

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

Leave a Comment