微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/css/218081.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。