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

前端之家收集整理的这篇文章主要介绍了将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.f2er.com/css/218081.html

猜你在找的CSS相关文章