可能重复:
How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?
让我说我有一个UIImage
我希望获得rgb矩阵,以便对其进行一些处理,而不是更改它,只需获取UIImage
数据,所以我可以使用我的C算法。
您可能知道,所有的数学运算都是在图像rgb矩阵上完成的。
答案 0 :(得分:3)
基本步骤是使用CGBitmapContextCreate
创建位图上下文,然后将图像绘制到该上下文中,并使用CGBitmapContextGetData
获取内部数据。这是一个例子:
UIImage *image = [UIImage imageNamed:@"MyImage.png"];
//Create the bitmap context:
CGImageRef cgImage = [image CGImage];
size_t width = CGImageGetWidth(cgImage);
size_t height = CGImageGetHeight(cgImage);
size_t bitsPerComponent = 8;
size_t bytesPerRow = width * 4;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
//Draw your image into the context:
CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage);
//Get the raw image data:
unsigned char *data = CGBitmapContextGetData(context);
//Example how to access pixel values:
size_t x = 0;
size_t y = 0;
size_t i = y * bytesPerRow + x * 4;
unsigned char redValue = data[i];
unsigned char greenValue = data[i + 1];
unsigned char blueValue = data[i + 2];
unsigned char alphaValue = data[i + 3];
NSLog(@"RGBA at (%i, %i): %i, %i, %i, %i", x, y, redValue, greenValue, blueValue, alphaValue);
//Clean up:
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
//At this point, your data pointer becomes invalid, you would have to allocate
//your own buffer instead of passing NULL to avoid this.