PNG Crush Automator Action

Apr 12, 2020

When using png files on the web it is often preferred to use tools like pngcrush on them to optimize their size. This is usually a manual process where a command line tool or website is used to process each image file. I decided to automate this process for me via macOS Automator.

To crush png images I use the opensource tool PNG Crush.

If you have Xcode installed, the pngcrush tool is included as a part of the iOS SDK and there is no additional download required.

If you do not have Xcode you may install PNG Crush via Homebrew using the following command.

1
brew install pngcrush

If using Xcode method, the pngcrush binary will be at /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/pngcrush.

If using Homebrew, the pngcrush binary will be at /usr/local/bin/pngcrush

For the rest of the article I will assume the Homebrew method is used. You just need to adjust the paths for the binary if the Xcode method is used.

To crush a PNG image via Terminal you can run the below command.

1
2
# pngcrush will process the input.png and create a compressed crushed.png
pngcrush input.png crushed.png

Automating the process using Automator on macOS.

  • Launch Automator via Spotlight Search.
  • Select File, New from the menu. Select Quick Action and click the Choose button.

Automator - New

  • In the new windows that loads, select the options as below.
    • Workflow receives current - image files
    • in - Finder.app

Automator - New Action

  • In the search box, type Shell and select the Run Shell Script option to add to the automation on the right by double clicking on it.

Automator - Run Shell Script

  • Change the Pass Input option to as arguments.
  • Enter the below script commands in the Shell Script box.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
for f in "$@"
do
    # Verify that the extension of the file is actually png
    # (case insensitive compare)
  filename=$(basename "$f")
  ext="${filename##*.}"
  if echo "$ext" | grep -i png; then
    # If the file is a png, run pngcrush on it.
    # Save the output in the same place with a temporary extension
    # of .crushed_
    /opt/homebrew/bin/pngcrush "$f" "$f.crushed_"
        # Overwrite the original file with the crushed file.
    mv "$f.crushed_" "$f"
  fi
done
  • Save the automation as PNG Crush.

Automator - Final Code

You may now browse to any png file(s) in Finder and right click, select Services -> PNG Crush.

Finder - Services Menu

While the automation is running you will see a spinning cog in you Menu bar in the top right. When the cog disappears the automation is done and your images have been processed by pngcrush.

Finder - Automator Running

WebAutomationTerminal

Building this website using open-source tools and hosting it for free

Catalina and Skype for Business Screensharing