Skip to content

Instantly share code, notes, and snippets.

@sakirsensoy
Last active November 21, 2024 01:15
Show Gist options
  • Save sakirsensoy/6edc4b21d75eff2f3c0a37aa4cc2483c to your computer and use it in GitHub Desktop.
Save sakirsensoy/6edc4b21d75eff2f3c0a37aa4cc2483c to your computer and use it in GitHub Desktop.
Wordpress Image Resizer / Optimizer

Wordpress Image Resizer / Optimizer

With wordpress there are a lot of plugins for optimizing previously uploaded images. Interestingly, almost all plugins direct you to use their own APIs for this task and charge high fees for this simple task. Whereas on our own server we can do it very simply. The image optimization function below will probably do the trick. I would base it on the ubuntu operating system, but you can easily find related packages for other operating systems.

Installation

Install required packages:

sudo apt install imagemagick pngquant

Add image optimizer method to .bashrc:

# WARNING: The method below will overwrite the same file.  
# If you want it to write a different file, you need to update the code accordingly.

function optimizeImage {
    imagePath=$1
    maxWidth=$2
    maxHeight=$3
    quality=$4
    filename=$(basename -- "$imagePath")
    directory=$(dirname -- "$imagePath")
    extension="${filename##*.}"
    filename="${filename%.*}"

    echo "Processing $imagePath"

    if [ "$extension" == "png" ]; then
        convert ${imagePath} -resize ${maxWidth}x${maxHeight} ${imagePath}
        pngquant ${imagePath} --force --quality=${quality} -o ${imagePath}
    else
        convert ${imagePath} -resize ${maxWidth}x${maxHeight} -quality ${quality} ${imagePath}
    fi
    
    echo "Done"
}

Reload .bashrc:

source ~/.bashrc

Usage example (resize and optimize single image):

optimizeImage "/var/www/html/wp-content/uploads/2024/04/image.png" 1400 1400 85

Usage example (resize and optimize multiple images):

declare -a files=("/var/www/html/wp-content/uploads/2024/04/image.png" "/var/www/html/wp-content/uploads/2024/04/image.jpg")

for i in "${files[@]}"
do
    optimizeImage $i 1400 1400 85
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment