-3

可能重复:
如何从 UIImage (Cocoa Touch) 或 CGImage (Core Graphics) 获取像素数据?

假设我有一个UIImage我想获得的 rgb 矩阵,以便对其进行一些处理,而不是更改它,只需获取UIImage数据,以便我可以在其上使用我的 C 算法。您可能知道,所有的数学运算都是在图像 rgb 矩阵上完成的。

4

1 回答 1

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.
于 2012-10-14T16:07:27.837 回答