-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 に答える