How do you write out a 16x16 PNG file for a file type icon in Cocoa? I tried this before with code like the snippet below. The snippet worked on a PPC machine with Mac OS X 10.5, but no longer seems to work on Mac OS X 10.6: the PNG that's written out has size 512x512, rather than 16x16.
NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFileType: NSFileTypeForHFSTypeCode(kGenericFolderIcon)];
[icon setSize: NSMakeSize(16.0,16.0)];
NSBitmapImageRep * bitmapRep = [NSBitmapImageRep imageRepWithData: [icon TIFFRepresentation]];
NSData * data = [bitmapRep representationUsingType: NSPNGFileType properties: nil];
[data writeToFile: @"/tmp/test.png" atomically: NO];
From what I understand from the documentation on NSImage
and NSImageRep
, the fact that the above code worked before was coincidence, as setSize:
only sets the "drawing size" of the image which doesn't necessarily match the "physical size" of its representation(s).
So what is the correct way to get the 16x16 size PNG file? Also, icons on Mac OS X can include a specially-drawn version for the 16x16 size, which is not just a scaled-down version of the "big" icon; how do you make sure this special version is written out to the PNG file when one is available?
If you are sure that there's a 16x16 sized version of the icon present in the NSImage, you could look through the representations (-[NSImage representations]
) and select the one you're interested in by looking at the size (-[NSImageRep pixelsWide]
and pixelsHigh
). You could then write the representation to disk.
A better way would be to create a 16x16 bitmap context, draw the image into that context and then save the contexts contents. This way also works if the original icon does not contain a 16x16 representation.