views:

162

answers:

2

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?

+2  A: 

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.

Carl Norum
This worked great but unfortunatley the method representationUsingType: is not supported by cocotron, and I need to be able to target cocotron as well. Can you suggest any other ways to accomplish this?
Mike2012
@Michael, edited answer to include a C library that will help you out.
Carl Norum
+2  A: 

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.

Peter Hosey
Thank you for your suggestion, but it seems that CGImageCreate is not supported by clozure (this is a common lisp - cocoa bridge) can you suggest any other alternatives to your method and the one listed above. Thanks for all your help!
Mike2012