Saving a 32 bit RGBA buffer into a .png file (Cocoa OSX)

送分小仙女□ 提交于 2019-12-10 17:19:30

问题


I need to save the contents of a pixel editor application into a .png file but I am having trouble finding the best way to accomplish this. The pixel data is stored in a 32 bit RGBA buffer. Can anyone suggest any good tools I could use to accomplish this?

EDIT: Unfortunately, CGImage and representationUsingType: are not supported by cocotron and I need to be able to target my app for PC release as well, can anyone suggest a third way of accomplishing this task?


回答1:


NSBitmapImageRep should get you what you need. Load the data up into the NSBitmapImageRep and then use representationUsingType:properties: to get it out as a PNG. A quick example:

NSBitmapImageRep *imageRep = 
    [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:imageBuffer
                                            pixelsWide:imageWidth
                                            pixelsHigh:imageHeight
                                         bitsPerSample:8
                                       samplesPerPixel:4
                                              hasAlpha:YES
                                              isPlanar:NO
                                        colorSpaceName:NSDeviceRGBColorSpace
                                          bitmapFormat:NSAlphaFirstBitmapFormat
                                           bytesPerRow:imageWidth * 4
                                          bitsPerPixel:32];
NSData *pngData = [imageRep representationUsingType:NSPNGFileType 
                                         properties:propertyDictionary];

If you can't use these Cocoa methods, check out libpng.




回答2:


Create a CGImage from the pixel data and feed it to a CGImageDestination.

Don't forget to finalize the destination before releasing it. That step is mandatory, and very easy to forget.



来源:https://stackoverflow.com/questions/2277418/saving-a-32-bit-rgba-buffer-into-a-png-file-cocoa-osx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!