2014-01-25 169 views
0

我用CIColorPosterize CIFilter绘制了一张带有图案的图像。该图像包含几个颜色。 在这一点上,我想提取一个UIColor的数组与该图像的n颜色。 有这样的功能吗?否则,这可能是一个有效的方法来实现这一点?获取图像中的所有颜色

谢谢专家!

+0

见http://stackoverflow.com/questions/16416380/iphone-how-to-get-colour-of-each-pixel-of-an-image为了一个灵感(哈哈无法添加它作为评论,因为我没有足够的声誉,但系统为我做了;)) – Janos

回答

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

10有用的方法。谢谢! –