Install packages on Ubuntu
apt-get install imagemagick optipng pngquant webp jpegoptim
Resize and compress
Configure this variable with your media path:
media='/home/deploy/magento/htdocs/pub/media'
Resize:
find $media -iregex '.*\.\(jpg\|png\|jpeg\)' -size +100k -exec mogrify -resize "1024x1024>" \{\} \;
Resize and compress:
find $media -iregex '.*\.\(jpg\|png\|jpeg\)' -size +100k -exec mogrify -resize "1024x1024>" -quality 10 \{\} \;
Compress png images:
find $media -iname "*.png" -size +100k -exec optipng -o7 {} \;
Compress png images (lossy):
find $media -iname "*.png" -size +100k -exec optipng -o7 {} \;
Compress jpegs (lossy):
find $media -iregex '.*\.\(jpg\|jpeg\)' -size +50k -exec jpegoptim --size=50k {} \;
Compress webp images:
find $media -iname "*.webp" -size +100k -exec cwebp -q 20 {} -o {} \;
Script to compress and resize media folder (lossy)
This script is useful to reduce disk size of folder media of a dev/stage environment.
Create script in your /usr/local/bin
folder:
tee /usr/local/bin/resize-images-very-lossy.sh <<'EOF'
#!/usr/bin/env bash
# bash script to heavily compress and resize images for a dev environment
if [[ $# -eq 0 ]]
then
media=$(pwd)
else
media=$1
fi
# resize all images
find $media -iregex '.*\.\(jpg\|png\|jpeg\)' -size +200k -exec mogrify -resize "1024x1024>" \{\} \;
# compress PNGs
find $media -iname "*.png" -size +100k -exec pngquant --speed 1 --ext .png -f {} \;
# compress JPEGs
find $media -iregex '.*\.\(jpg\|jpeg\)' -size +100k -exec jpegoptim --size=80k {} \;
# compress WEBP images
find $media -iname "*.webp" -size +100k -exec cwebp -q 20 {} -o {} \;
# compress all images
find $media -iregex '.*\.\(jpg\|png\|jpeg\)' -size +100k -exec mogrify -resize "1024x1024>" -quality 5 \{\} \;
EOF
chmod +x /usr/local/bin/resize-images-lossy.sh
Usage:
resize-images-very-lossy.sh /path/to/magento/dev-staging/media/folder/
Setup a daily cronjob (as root):
tee /etc/cron.daily/resize-images-very-lossy <<'EOF'
#!/bin/bash
/usr/local/bin/resize-images-very-lossy.sh /path/to/magento/dev-staging/media/folder/
# replace with your mage user
chown -R mageuser:mageuser /path/to/magento/dev-staging/media/folder/
EOF
Leave a Reply