Resume

Tuesday, January 29, 2013

How to batch convert using sips on Mac

Have you ever had a bunch of images that you needed to quickly convert into a different format? I have! The Mac has some great tools like GraphicConverter and PhotoShop, but it also has a flexible command line image converter that comes with every Mac: sips, the scriptable image processing system.

I had a problem where I had a lot of web images in different formats (png, jpg, gif) and wanted to run a scenario of how much space I'd be able to save by converting all the images to low-quality jpeg. The following bash script expects a wildcard argument (e.g., *.jpg, *.gif, *.*) then creates a directory 'low' and makes low-quality versions of all the images in the argument in the low directory.
#!/bin/bash
FILES="$@"
if ! [-d 'low']       # if low doesn't exist, make it
  then mkdir 'low';
fi
for i in $FILES; 
do
  # find the extension on files that may have multiple periods or
  # extensions like 'jpeg'
  NF=$(echo $i | awk -F "." '{print NF}');  
  NF=$(($NF - 1));
  EXT=$(echo $i | awk -F "." '{print $NF}');
# convert image using 50% quality and save in 'low' folder as jpg
  sips -s format jpeg -s formatOptions 50% $i --out "low/"$(echo $i | sed "s/"$EXT"/jpg/g")
done