2016年8月10日 星期三

iOS RGBA rawdata to UIImage

int dstW = 640;
int dstH = 480;
int bufferLength = dstW * dstH * 4;
unsigned char *dst = (unsigned char*) calloc(bufferLength, sizeof(unsigned char));

// do something on buffer dst

CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, dst, bufferLength, NULL);
int bitsPerPixel = 32;
colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGImageRef dstImageRef = CGImageCreate(dstW, dstH, bitsPerComponent, bitsPerPixel, dstW * 4, colorSpaceRef,
                                       bitmapInfo, provider, NULL, NO, renderingIntent);
UIImage *dstImg = [UIImage imageWithCGImage: dstImageRef];

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);

iOS save picture to App document folder

/* create path to cache directory inside the application's Documents directory */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex: 0] stringByAppendingPathComponent: @"output.jpg"];
NSData *photoData = UIImageJPEGRepresentation(dstImg, 1);
[photoData writeToFile:filePath atomically: YES];