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.
sudo apt install imagemagick pngquant
# 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"
}
source ~/.bashrc
optimizeImage "/var/www/html/wp-content/uploads/2024/04/image.png" 1400 1400 85
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