Thursday, February 9, 2012

Convert Images to JPG with Automator an ImageMagick

There are several guides online that discuss how to add a context menu that allows you to convert images to .jpg format. You essentially start with a new Automator Service and then use it to copy and convert those images.

Two problems:

  1. The resulting image is not "[filename].jpg", but rather "[filename] copy.jpg"
  2. The result must be stored in a "temp" directory (Desktop or elsewhere) and when it does, the process creates an intermediate file which then gets deleted, leaving a "gap" on your Desktop
Being a bash (command line) junkie, I wanted a more elegant solution that would:
  1. Preserve the filename (changing the extension only)
  2. Create the resulting file in the same directory as the original
Luckily, the bash script is simple and elegant (and also works with filenames that contain extra dots in the name, like "Screen Shot 2012-02-09 at 10.57.48 AM.png"):

for img in "$@"; do
filename=${img%.*}
convert "$img" -background white -flatten "$filename.jpg"
done

The 'convert' function is actually part of the ImageMagick suite of image manipulation tools. I installed mine through MacPorts, so it is actually located at

/opt/local/bin/convert

so you may need to adjust your settings to match your machine path.

Alright, first step, open /Applications/Automator:


You want to choose 'Service' from this menu. If you don't see a side bar on the left for all of your available actions, click the Show Library icon:


 should become 

You will see a section at the top that says "Service receives selected...":


You want to change this to 'image files' and the "in" should change to 'Finder':


Next, select the "Utilities" option on the left and find "Run Shell Script" in the list next to it:


Drag-and-drop this onto the main window and change the "Pass input" from 'to stdin' to 'as arguments'. You will get a default for loop:


 Simply copy-and-paste the code above into this box and save the Workflow:


Save this file to something memorable, like "Image to JPG". When you do, you will have a NEW context menu element that you can use:


Click that and you get a new shiny "[filename].jpg" in the same folder as the original (be it PNG, TIFF, etc.)!

If you would prefer to trash the old filename, you can choose to use the ImageMagick command 'mogrify' instead of 'convert' (such as found at places like puddingbowl).

No comments:

Post a Comment