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

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

EDIT: Unfortunately, CGImage and presentationUsingType: are not supported by the cocotron, and I need to also target my PC release application, can anyone suggest a third way to accomplish this task?

+4
source share
2 answers

NSBitmapImageRep should provide you with what you need. Load the data into NSBitmapImageRep and then use representationUsingType:properties: to get it as PNG. 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 cannot use these Cocoa methods, check out libpng .

+5
source

Create a CGImage from the pixel data and pass it a CGImageDestination .

Remember to complete to the end before releasing it. This step is a must and very easy to forget.

+2
source

Source: https://habr.com/ru/post/1301516/


All Articles