一般提取方法(RGBA)
// 提取图像数据
UIImage *srcImage = [UIImage imageNamed:@"test"];
CGImageRef cgImage = [srcImage CGImage];
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));
const unsigned char *rgba = CFDataGetBytePtr(data);
// 释放内存
CFRelease(data);
去除 alpha 通道的(RGB)
// 提取 RGBA 图像数据,可以用上面的方法,但是内存占用会大些
UIImage *srcImage = [UIImage imageNamed:@"test"];
CGImageRef image = [srcImage CGImage];
CGSize size = srcImage.size;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
int pixelCount = size.width * size.height;
uint8_t* rgba = malloc(pixelCount * 4);
CGContextRef context = CGBitmapContextCreate(rgba, size.width, size.height, 8, 4 * size.width, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), image);
CGContextRelease(context);
// 移除 alpha 通道
uint8_t* rgb = malloc(pixelCount * 3);
int m = 0;
int n = 0;
for(int i=0; i<pixelCount; i++){
rgb[m++] = rgba[n++];
rgb[m++] = rgba[n++];
rgb[m++] = rgba[n++];
n++;
}
free(rgba);
// 使用完之后释放内存
free(rgb);
网友评论