2012-10-14 63 views
-3

可能重複:
How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?DSP上的UIImage

比方說,我有一個UIImage,我想獲得的RGB矩陣,以做一些關於它的處理,不要更改它,只需獲取UIImage數據,以便我可以使用我的C算法就可以了。你可能知道,所有的數學都是在圖像rgb矩陣上完成的。

+2

@userxxx而不是隨機插入不相關的代碼,使您的問題達到SO的質量標準。沒有別的辦法。 – 2012-10-14 16:32:09

+0

之前和之前,使用搜索! – vikingosegundo

+0

@ H2CO3所以,你能教我如何做到這一點?我想知道爲了讓我成爲「品質」,我必須改變什麼?這真的讓我感興趣。 – user1280535

回答

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. 
+0

非常感謝。很好的答案。 – user1280535