Search code examples
iphoneiphone-sdk-3.0

IPHONE: How do I extract the RGB channels of a UIIMage?


I have an UIImage with alpha channel.

How do I extract the RGB channels of a UIImage, each one to be an independent UIImage with alpha?

thanks in advance.


Solution

  • Like this.

    Also, take a look at this question - third answer in paranoid detail
    And some code for accessing the pixels and saving them into a new UIImage:

    UIImage* image = ...; // An image
    NSData* pixelData = (NSData*) CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
    void* pixelBytes = [pixelData bytes];
    
    //Leaves only the green 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] = 0; // blue
            bytes[i+3] = 0; // alpha
        }
    
    NSData* newPixelData = [NSData dataWithBytes:pixelBytes length:[pixelData length]];
    UIImage* newImage = [UIImage imageWithData:newPixelData];
    

    adapted from here. To have the three distinct channels in separate images, do like in the code, set to zero all but the channel that you want to save each time, and then create the new image.