Friday, November 12, 2010

Get pixel from UIImage to do Image Processing:


This is a sample for converting image to grayscale. In this example, we can know how to get pixel from UIImage to do some Image Processing.




- (UIImage *)convertToOpaque:(UIImage *)image toEndPoint:(CGPoint)point
{
    int width = image.size.width;
    int height = image.size.height;

    // the pixels will be painted to this array
    uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));

    // clear the pixels so any transparency is preserved
    memset(pixels, 0, width * height * sizeof(uint32_t));
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    // create a context with RGBA pixels
    CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, 
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);

    // paint the bitmap to our context which will fill in the pixels array
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), [image CGImage]);

    // Here you can get rgba Pixel and you can do any thing with this rgba 
    //alpha at rgbaPixel[0], Red at rgbaPixel[1], Green at rgbaPixel[2], Blue at rgbaPixel[3]

  for (int y=0; y<height; y++) {
    for (int x=0; x<width; x++) {
        uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];
                  /*****************************
                   Do something here
                   For example:
                   int average = (rgbaPixel[1] + rgbaPixel[2] + rgbaPixel[3]) / 3;
                   rgbaPixel[1] = average;
                   rgbaPixel[2] = average;
                   rgbaPixel[3] = average;
                   *****************************/
    }
  }

  // create a new CGImageRef from our context with the modified pixels
    CGImageRef rImage = CGBitmapContextCreateImage(context);

    // we're done with the context, color space, and pixels
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    free(pixels);

    // make a new UIImage to return
    UIImage *resultUIImage = [UIImage imageWithCGImage:rImage];

    // we're done with image now too
    CGImageRelease(rImage);
    return resultUIImage;
}


By Dragon

No comments:

Post a Comment