-3

Possible Duplicate:
How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

Let's say I have a UIImage that I would like to get the rgb matrix of, in order to do some processing on it, not to change it, just get the UIImage data so i can use my C algorithms on it. As you probably know, all the math is done on the image rgb matrixes.

Community
  • 1
  • 1
user1280535
  • 347
  • 3
  • 13
  • 2
    @userxxx instead of randomly inserting unrelated code, make your question hit the quality standards of SO. There's no other way. –  Oct 14 '12 at 16:32
  • and before you do so, use the search! – vikingosegundo Oct 14 '12 at 16:34
  • @H2CO3 so, can you teach me how to do that ? i would like to know what do i have to change in order to make me be "quality" ? this is really interested me . – user1280535 Oct 14 '12 at 16:40
  • @user1280535 you have to post a specific question about a specific problem (that's good in this question as far as I can tell you). Your question should be written in good and understandable English. Then you should make sure your question cannot be answered using a simple google search or a search on StackOverflow (this one can). To complete all this, off-topic or spam (self-promoting and advertising) non-questions are not welcome. –  Oct 14 '12 at 16:45

1 Answers1

3

The basic procedure is to create a bitmap context with CGBitmapContextCreate, then draw your image into that context and get the internal data with CGBitmapContextGetData. Here's an example:

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.
omz
  • 53,243
  • 5
  • 129
  • 141