"Get pixel information from UIImage"

Sun 04 October 2009

UIImage *uiImage = [UIImage imageNamed:@"myimage.png"];

CGImageRef image = uiImage.CGImage;

NSUInteger width = CGImageGetWidth(image);

NSUInteger height = CGImageGetHeight(image);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

UInt8 * rawData = malloc(height * width * 4);

 

int bytesPerPixel = 4;

int bytesPerRow = bytesPerPixel * width;

 

NSUInteger bitsPerComponent = 8;

CGContextRef context1 = CGBitmapContextCreate(

rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace,

kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big

);

CGColorSpaceRelease(colorSpace);

 

CGContextDrawImage(context1, CGRectMake(0, 0, width, height), image);

CGContextRelease(context1);

 

//Now to get byte for ppixel you need to call

//rawData[x * bytesPerRow  + y * bytesPerPixel]