Monday, August 6, 2018

Icon, therefore I am.

    We recently discovered that the common method for setting file icons using sips, DeRez, Rez, and SetFile has stopped working on High Sierra. Sips seems to have removed the function needed, instead printing "addIcon is no longer supported". After a bit of digging and combining existing code, I found that getting and setting a file/folder icon is pretty easy.

This script allows you to either 1) export an icon from a file path or 2) set a file icon from an image. Usage is:

Export Icon:
./ /path/to/file.ext
Set Icon:
./ /path/to/icon.img /path/to/set/file.ext
 Code (also on GitHub)
#!/usr/bin/python# python script that extract an icon from an OSX file and save it at jpeg#
from AppKit import *
import sys, Cocoa
if len(sys.argv) == 2:
    print "One argument"
    for path in sys.argv[1:]:
        print path
        NSBitmapImageRep.imageRepWithData_(NSWorkspace.sharedWorkspace().iconForFile_(path).TIFFRepresentation()).representationUsingType_properties_(NSJPEGFileType, None).writeToFile_atomically_(path+".jpg", None)
elif len(sys.argv) == 3:
    print "Two argument"
    NSWorkspace.sharedWorkspace().setIcon_forFile_options_(Cocoa.NSImage.alloc().initWithContentsOfFile_(sys.argv[1].decode('utf-8')), sys.argv[2].decode('utf-8'), 0) or sys.exit("Unable to set file icon")
    print "Get Icon with path to file"
    print "Set Icon with path to icon, path to file"

No comments: