2014-01-25 119 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有用的方法。謝謝! –