GetIcon.m

May 26, 2009

Shell scripting is awesome, but there are situations where it just won’t help you. Like when you’re supposed to save the full-res icon of any file as a PNG image.

Luckily it’s quite easy with a bit of ObjC. This is what I threw together for this particular problem:

# GeIcon.m
# Save icon of given path as a PNG image
#import <AppKit/AppKit.h>

int main (int argc, const char * argv[])
{
    if (argc < 2) {
      printf("Usage: GetIcon input output");
      return 1;
    }

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *imgPath = [NSString stringWithCString:argv[1]];
    NSString *outPath = [NSString stringWithCString:argv[2]];

    NSWorkspace *ws = [NSWorkspace sharedWorkspace];
    NSImage *img = [ws iconForFile:imgPath];
    NSData *data = [img TIFFRepresentation];
    NSBitmapImageRep *bits = [NSBitmapImageRep imageRepWithData:data];
    NSData *imgData = [bits representationUsingType:NSPNGFileType properties:nil];
    [imgData writeToFile:outPath atomically:NO];

    [pool drain];
    return 0;
}

If anyone know how to do this using shell tools, please let me know. ;-)