2016年8月10日 星期三

iOS UIImage to RGBA rawdata

UIImage *image = [UIImage imageNamed: @"test.jpg"];
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
NSUInteger bufferLength = width * height * 4;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(bufferLength, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpaceRef,
kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpaceRef);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
free(rawData);

沒有留言:

張貼留言