如何提取图像的RGB值?

问题描述:

而不是使用[UIColor colorWithPatternImage:[UIImage imageNamed:@"my_image.png"]];从图像设置视图的背景颜色, 下次我只想使用检索到的RGB值来设置我的视图的背景颜色。如何提取图像的RGB值?

+0

目前还不清楚你在这里问什么。 – buildsucceeded

希望你正在寻找我从其他来源复制的这个。

+ (NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)x andY:(int)y count:(int)count{ 
NSMutableArray *result = [NSMutableArray arrayWithCapacity:count]; 

// First get the image into your data buffer 
CGImageRef imageRef = [image CGImage]; 
NSUInteger width = CGImageGetWidth(imageRef); 
NSUInteger height = CGImageGetHeight(imageRef); 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char)); 
NSUInteger bytesPerPixel = 4; 
NSUInteger bytesPerRow = bytesPerPixel * width; 
NSUInteger bitsPerComponent = 8; 
CGContextRef context = CGBitmapContextCreate(rawData, width, height, 
       bitsPerComponent, bytesPerRow, colorSpace, 
       kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 
CGColorSpaceRelease(colorSpace); 

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); 
CGContextRelease(context); 

// Now your rawData contains the image data in the RGBA8888 pixel format. 
NSUInteger byteIndex = (bytesPerRow * y) + x * bytesPerPixel; 
for (int i = 0 ; i < count ; ++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; 
    byteIndex += bytesPerPixel; 

    UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; 
    [result addObject:acolor]; 
}free(rawData);return result;}'