Rea*_*ion 18 rgb cocoa bitmap objective-c objective-c++
我有一个RGB unsigned char的缓冲区,我想将其转换为位图文件,有谁知道怎么做?
我的RGB float具有以下格式
R [(0,0)],G [(0,0)],B [(0,0)],R [(0,1)],G [(0,1)],B [(0, 1)],R [(0,2)],G [(0,2)],B [(0,2)] .....
每个数据单元的值范围从0到255.任何人都有任何想法如何进行此转换?
nsc*_*idt 34
您可以使用CGBitmapContextCreate从原始数据创建位图上下文.然后,您可以从位图上下文创建CGImageRef并保存它.不幸的是,CGBitmapContextCreate对数据的格式有点挑剔.它不支持24位RGB数据.开头的循环将rgb数据调到rgba,结尾处的alpha值为零.您必须包含ApplicationServices框架并与之链接.
char* rgba = (char*)malloc(width*height*4);
for(int i=0; i < width*height; ++i) {
rgba[4*i] = myBuffer[3*i];
rgba[4*i+1] = myBuffer[3*i+1];
rgba[4*i+2] = myBuffer[3*i+2];
rgba[4*i+3] = 0;
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bitmapContext = CGBitmapContextCreate(
rgba,
width,
height,
8, // bitsPerComponent
4*width, // bytesPerRow
colorSpace,
kCGImageAlphaNoneSkipLast);
CFRelease(colorSpace);
CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR("image.png"), kCFURLPOSIXPathStyle, false);
CFStringRef type = kUTTypePNG; // or kUTTypeBMP if you like
CGImageDestinationRef dest = CGImageDestinationCreateWithURL(url, type, 1, 0);
CGImageDestinationAddImage(dest, cgImage, 0);
CFRelease(cgImage);
CFRelease(bitmapContext);
CGImageDestinationFinalize(dest);
free(rgba);
Run Code Online (Sandbox Code Playgroud)