View Single Post
  #1   (View Single Post)  
Old 27th October 2017
demifiend's Avatar
demifiend demifiend is offline
Real Name: Matthew Graybosch
Silent Protagonist
 
Join Date: Oct 2017
Location: Harrisburg, PA
Posts: 29
Default bash script to resize and optimize images using ImageMagick and jpegoptim

GarryR requested that I share this in the "Your Favorite Programing Language" thread, so here it is. There's some code for PNG files that also uses pngcrush, but it still needs work.

Code:
#!/usr/bin/env ksh

# © 2017 Matthew Graybosch (public@matthewgraybosch.com)
# Released under the 3-Clause BSD License
# See https://opensource.org/licenses/BSD-3-Clause for details

# NEVER RUN THIS AS PART OF THE BUILD PROCESS ON TRAVIS CI! 
# IT TAKES TOO LONG AND CAUSES TIMEOUTS.
# RUN THIS SCRIPT LOCALLY, COMMIT, AND PUSH TO MASTER.

# We need to resize and compress images for display. 
# Script based on "Efficient Image Resizing With ImageMagick" by Dave Newton
# https://www.smashingmagazine.com/2015/06/efficient-image-resizing-with-imagemagick/

function processJPG {
  for img in ${1}*.jpg
  do
    convert $img -resize ${2} -filter Triangle -define filter:support=2 -unsharp 0.25x0.25+8+0.065 -dither None -posterize 136 -define jpeg:fancy-upsampling=off -colorspace sRGB $img;
    jpegoptim --all-progressive --strip-all $img;
  done
}

function processPNG {
  for img in ${1}*.png
  do
	convert $img -resize ${2} -filter Triangle -define filter:support=2 -unsharp 0.25x0.25+8+0.065 -dither None -posterize 136 -define png:fancy-upsampling=off $img;
	pngcrush -d ${3} -brute -reduce $img;
  done
}

echo "STARTED image processing..."
export INPUT_PATH=./images/incoming/
export ORIGINALS=./images/originals/
export TEMP=./images/tmp/
export OUTPUT_PATH=./assets/images/
export OUTPUT_WIDTH=768

echo "Copying images to processing directories..."
cp ${INPUT_PATH}* $OUTPUT_PATH
cp ${INPUT_PATH}* $TEMP
mv ${INPUT_PATH}* $ORIGINALS

echo "Resizing images..."
processJPG $OUTPUT_PATH $OUTPUT_WIDTH;
processPNG $TEMP $OUTPUT_WIDTH $OUTPUT_PATH;

echo "FINISHED image processing..."
__________________
OpenBSD 6.2-RELEASE on Thinkpad T430s, ThinkCentre M92P, and Clevo W24AEU
Web | Keybase | Mastodon | GitHub
"What happens in the TARDIS stays in the TARDIS."

Last edited by demifiend; 27th October 2017 at 02:26 AM. Reason: Corrected JPG resize command. Fixed pngcrush command. Changed shell to ksh.
Reply With Quote