Monday, March 17th, 2025 | Server
Last Modified: 2025-07-15
If your Linux server is getting bogged down by large image files, you can automate the process of resizing and compressing them using a simple Bash script. This guide will help you set up an automated image optimization process.
You'll need ImageMagick, jpegoptim, and pngquant for resizing and optimizing images.
sudo dnf install epel-release -y
sudo dnf install imagemagick jpegoptim pngquant -y
Create a script called shrink_images.sh and paste the following:
#!/bin/bash
# Set the target size limit (1.5MB = 1536k)
SIZE_LIMIT="+1536k"
# Find and process JPEG and PNG images
find /var/www -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) -size $SIZE_LIMIT | while read file; do
echo "Processing: $file"
# Resize images larger than 1920px while keeping aspect ratio
convert "$file" -resize '1920x1920>' "$file"
# Optimize JPEG files
if [[ $file == *.jpg || $file == *.jpeg ]]; then
jpegoptim --strip-all --max=80 "$file"
fi
# Optimize PNG files
if [[ $file == *.png ]]; then
pngquant --force --ext .png --quality=65-80 "$file"
fi
done
echo "Image optimization completed!"
After saving the script, give it execution permissions:
chmod +x shrink_images.sh
To manually optimize images, run:
./shrink_images.sh
To automate the process, schedule it with cron:
crontab -e
Add this line to run the script every night at midnight:
0 0 * * * /path/to/shrink_images.sh >> /var/log/shrink_images.log 2>&1
To check disk space before and after optimization, use:
du -sh /var/www
With this script, you can automatically resize and compress large images, improving your server performance and saving disk space.
Happy optimizing!
Input Action Output
A collection of snippets and links that have proven useful for development and programming in ColdFusion, JavaScript, jQuery, PHP, Python, Dell, Minecraft, Apple, Mac, Windows, LINUX, Raspberry Pi, Adobe, CSS, and HTML.
©2025 Input Action Output