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:
./fileIcon.py /path/to/file.ext
Set Icon:
./fileIcon.py /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# https://superuser.com/questions/133784/manipulate-mac-os-x-file-icons-from-automator-or-command-line
# https://apple.stackexchange.com/questions/6901/how-can-i-change-a-file-or-folder-icon-using-the-terminal/198714
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")
 
else:
    print "Get Icon with path to file"
    print "Set Icon with path to icon, path to file"

No comments: