Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compress Magento media from commandline
# you need these installed if you want to:
sudo apt-get update
# resize images
sudo apt-get install imagemagick -y
# compress jpg and png files
sudo apt-get install jpegoptim optipng
# compress video's
sudo apt-get install ffmpeg
# cd into your Magento media e.g.
cd /var/www/html/magento/pub/media
# list the directories that contain images you want to resize / compress. Separated by a space.
folders=('wysiwyg' 'catalog/category' 'catalog/product' 'blog' 'gallery')
# set the max allowed height for images
WIDTH=1920
# set the max allowed width for images
HEIGHT=1200
# search for jpg/jpeg/png files and resize them to max width/height, keeping aspect ration
find ${folders[@]} \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' \) -exec convert \{} -verbose -resize $WIDTHx$HEIGHT\> \{} \;
# find all jpg/jpeg files and run them through jpegoptim to compress them
find "${folders[@]}" \( -iname '*.jpg' -o -iname '*.jpeg' \) -type f -print0 | xargs -0 jpegoptim -o --max=90 --strip-all --all-progressive >/dev/null 2>/dev/null
# find all png files and run them through optipng
find "${folders[@]}" -iname '*.png' -type f -print0 | xargs -0 optipng -o2 -strip all
# list the directories that contain videos you want to compress. Separated by a space.
folders=('video')
# compress videos in a given directory
find ${folders[@]} \( -iname '*.mpg -o -iname '*.mpeg' -o -iname '*.mp4' \) -exec ffmpeg -i \{} -an -c:v libx264 -crf 32 \{} \;
# You could run the above commands in a cronjob, only updating files that were modified in the last 24 hours
folders=('resized' 'wysiwyg' 'catalog/category' 'catalog/product' 'blog')
# max height
WIDTH=1920
# max width
HEIGHT=1200
find ${folders[@]} \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' \) -mtime -1 -exec convert \{} -verbose -resize $WIDTHx$HEIGHT\> \{} \;
find "${folders[@]}" \( -iname '*.jpg' -o -iname '*.jpeg' \) -mtime -1 -type f -print0 | xargs -0 jpegoptim -o --max=90 --strip-all --all-progressive >/dev/null 2>/dev/null
find "${folders[@]}" -iname '*.png' -mtime -1 -type f -print0 | xargs -0 optipng -o2 -strip all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.