Skip to content

Instantly share code, notes, and snippets.

@Che4ter
Created March 17, 2017 08:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Che4ter/434b1f8e4b7133405b94a88d460c49b9 to your computer and use it in GitHub Desktop.
Save Che4ter/434b1f8e4b7133405b94a88d460c49b9 to your computer and use it in GitHub Desktop.
Bulk mozjpeg optimizer on the current directory, works with spaces in filename
#!/bin/bash
# Compresses all .jpg/.jpeg and saves them to opt/
# works with spaces in filenames
# make sure you adjust the path to mozjpeg bin
# uses the mozilla mozjpeg encoder from https://github.com/mozilla/mozjpeg
# based on https://gist.github.com/sauramirez/e0ef5059ab637ed3e2cea090b504f385
# Che4ter - 2017
#Change to mozjpeg path
MOZJPEG='/opt/mozjpeg/bin/'
GREEN='\033[0;32m'
NC='\033[0m'
mkdir -p opt
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
shopt -s nullglob
for image in *.jpg *.jpeg
do
printf "${GREEN}Compressing${NC} ${image}\n"
${MOZJPEG}djpeg ${image} | ${MOZJPEG}cjpeg -quality 80 | ${MOZJPEG}jpegtran -optimize > opt/${image}
done
IFS=$SAVEIFS
@westofer
Copy link

really helpful, works great! thanks

AUR users should install mozjpeg-opt if they don't want to change MOZJEPG path

@djmalibiran
Copy link

I'm converting multiple images to multiple formats (Avif, WebP, MozJPEG). The following is my file management and I honestly don't want to change it:

parentFolder
| mozjpeg.sh
| webp.sh
| avifNode.txt
| inputFolder
| outputFolder
| webpAssets
| mozjpegAssets

The following is what is in the mozjpeg.sh:

MOZJPEG='C:\parentFolder\mozjpegAssets\Release\'

GREEN='\033[0;32m'
NC='\033[0m'

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
shopt -s nullglob
for image in inputFolder/*.jpg
do
  printf "${GREEN}Compressing${NC} ${image}\n"
  ${MOZJPEG}djpeg ${image} | ${MOZJPEG}cjpeg -quality 85 | ${MOZJPEG}jpegtran -optimize -progressive > outputFolder/${image}
done
IFS=$SAVEIFS

This^ is working just fine.
The only problem is the optimized images are being saved in parentFolder > outputFolder > inputFolder. What I want is the optimized images must be saved in parentFolder > outputFolder.

I hope you can help me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment