Observation Point

1 note

Setting Custom Icon on Folders in Mac OS X from the Command Line

While working on creating the distribution script for packaging the Singly iOS SDK, I ran into a number of issues trying to automatically assign a custom icon to one of the distributed folders. I searched and found a myriad of solutions, but they all suffered from one or more problems:

  • the embedded icon was not high-resolution, so it looked terrible when scaled,
  • or you could not use an ICNS bundle directly without extracting an image from it,
  • or most of the command examples did not function properly on Mountain Lion.

So after much trial and error, I finally came up with a solution that would address all of the above issues.  The following assumes that you already have an ICNS bundle containing your icon at various resolutions.

Step 1 — Create Folder w/Custom Icon

The first thing we need to do is create a temporary folder in Finder and set our ICNS bundle as its icon via Finder’s Inspector:

  • Create a new folder (for this example we’ll use “tempfolder” as the name) in Finder.
  • Right-click on the folder and select “Get Info” from the context menu.
  • Drag your icon file and drop it onto the standard blue folder icon at the top left of the Inspector window.

Step 2 — Extract the Icon Resource

Now that we have a folder with our custom icon set correctly, we will need to extract the resource fork containing our icon. Open the Terminal and execute the following command:

DeRez -only icns path/to/tempfolder/$'Icon\r' > MyIcon.rsrc

This will extract the properly formatted icon resource into a separate file that we will use later.  You can now trash the temporary folder we created in step 1.

Step 3 — Apply the Icon Resource

Once we have the extracted resource file, we can apply it to any folder (or file) of our choosing at anytime from the command-line (or a script). This is useful if you need to automate the process of setting a custom icon on a generated folder, such as when you are packaging a new release.

To apply the custom icon to your folder, execute the following in Terminal (or from a script):

Rez -append path/to/MyIcon.rsrc -o path/to/folder/$'Icon\r'
SetFile -a C path/to/folder

That’s it!

Be sure to keep your extracted resource file around so you can use it in the future.

Filed under osx