问题
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