从图像中获取所有颜色

时间:2014-01-25 11:45:14

标签: ios objective-c image-processing uiimage cifilter

我有一张CIColorPosterize CIFilter的海报图片。图像包含少量颜色。 此时我想从这张图片中提取一个带有n色的UIColor数组。 有一个功能可以做这样的事情吗? 否则,这可能是实现这一目标的有效方法吗?

谢谢专家!

1 个答案:

答案 0 :(得分:2)

你可以试试这个..

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);