4

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?

Mike2012
  • 7,629
  • 15
  • 84
  • 135

2 Answers2

5

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
  • 219,201
  • 40
  • 422
  • 469
  • 1
    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 Feb 19 '10 at 22:20
  • @Michael, edited answer to include a C library that will help you out. – Carl Norum Feb 19 '10 at 22:36
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.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
  • 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 Feb 19 '10 at 22:21