iPhone:如何获取图像每个像素的颜色?

我想获得图像中所有单个像素的颜色。 详细说明我说有一个名为“SampleImage”的图像有400 x 400像素基本上我想从’SampleImage’创建一个网格,它将有400 x 400个正方形,每个正方形填充对应于’SampleImage’中特定像素的颜色。

我知道这有点抽象,但我是iOS的新手,不知道从哪里开始。 提前致谢!

使用此:这是更有效的解决方案:

// UIView+ColorOfPoint.h @interface UIView (ColorOfPoint) - (UIColor *) colorOfPoint:(CGPoint)point; @end // UIView+ColorOfPoint.m #import "UIView+ColorOfPoint.h" #import  @implementation UIView (ColorOfPoint) - (UIColor *) colorOfPoint:(CGPoint)point { unsigned char pixel[4] = {0}; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast); CGContextTranslateCTM(context, -point.x, -point.y); [self.layer renderInContext:context]; CGContextRelease(context); CGColorSpaceRelease(colorSpace); //NSLog(@"pixel: %d %d %d %d", pixel[0], pixel[1], pixel[2], pixel[3]); UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0]; return color; } @end 

希望它能帮到你。

这段代码对我来说完美无缺 – :

  - (NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)xx andY:(int)yy 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. int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel; for (int ii = 0 ; ii < count ; ++ii) { 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 += 4; UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; [result addObject:acolor]; } free(rawData); return result; } 

如果你是一个新手,你应该考虑先做一些事情。 无论如何,你需要做的是通过CGBitmapContextCreate设置一个CGContextRefCGBitmapContextCreate有足够的数据来保存你的图像。 创建后,需要通过CGDrawImage将图像渲染到其中。 之后,您将拥有指向图像中每个像素的指针。 该代码类似于Nishant的答案,但不是1×1,而是使用400×400来同时获取所有像素。