Search code examples
iosobjective-cimage-processinguiimagecifilter

Get all colors from an image


I have a posterized image with CIColorPosterize CIFilter. The image contains a few number of colors. At this point I would like to extract an UIColor's array with the n-colors from this image. There is a function that does something like this? Otherwise, which could be an effective approach to realize this?

Thank you experts!


Solution

  • You can try this..

    CGImageRef imageRef = [yourImage CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    
    // Now your rawData contains the image data in the RGBA8888 pixel format.
    int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
    for (int i = 0 ; i < count ; byteIndex += 4,++i)
    {
        CGFloat red   = (rawData[byteIndex]     * 1.0) / 255.0;
        CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
        CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0;
        CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;    
        UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
        [result addObject:acolor];
    }
    
    free(rawData);
    NSLog(@"Extracted colors count %d",result.count);