将RGB数据转换为Objective-C Cocoa中的位图

我有一个RGB unsigned char的缓冲区,我想转换成一个位图文件,有没有人知道如何?

我的RGB浮点是以下格式

R [(0,0)],G [(0,0)],B [(0,0)],R [(0,1)],G [(0,1) 1]],R [(0,2)],G [(0,2)],B [(0,2)] …..

每个数据单元的值的范围是0到255.任何人有什么想法可以如何进行这种转换?

解决方法

您可以使用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);

相关文章

Css常用的排序方式权重分配 排序方式: 1、按类型&#160;...
原文:https://www.cnblogs.com/wenruo/p/9732704.html 先上...
css属性:word-wrap:break-word; 与 word-break:break-all 的...
https://destiny001.gitee.io/color/
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML...
css之background的cover和contain的缩放背景图 对于这两个属...