const NSUInteger bitsPerComponent = 8;
const NSUInteger bytesPerPixel = 4;
/**
return r,g,b,a
*/
+ (NSData*)getRGBAsFromImage:(UIImage*)image atX:(int)xx andY:(int)yy count:(int)count
{
// First get the image into your data buffer
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
NSUInteger size = height * width * bytesPerPixel;
NSUInteger bytesPerRow = bytesPerPixel * width;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsignedchar *rawData = (unsignedchar*) calloc(size, sizeof(unsignedchar));
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
NSData *data = [NSData dataWithBytes:rawData length:count];
CGContextRelease(context);
free(rawData);
CGColorSpaceRelease(colorSpace);
return data;
}
+ (void)setImageFromData:(NSData*)data width:(NSUInteger)width height:(NSUInteger)height destImage:(UIImage**)destImage
{
Byte *rawData = (Byte *)data.bytes;
CFIndex count = data.length;
NSUInteger bytesPerRow = bytesPerPixel * width;
CFDataRef rgbData = CFDataCreate(NULL, rawData, count);
CGDataProviderRef provider = CGDataProviderCreateWithCFData(rgbData);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGImageRef imageRef = CGImageCreate(width,
height,
bitsPerComponent,
bytesPerPixel * 8,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big,
provider,
nil,
NO,
kCGRenderingIntentDefault);
*destImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGColorSpaceRelease(colorSpace);
CGDataProviderRelease(provider);
CFRelease(rgbData);
}
參考資料:
http://stackoverflow.com/questions/2261177/cgimage-from-byte-array
http://stackoverflow.com/questions/2838038/c-programming-malloc-inside-another-function
留言列表