/bash/

Compress web images

2020-04-19 14:00:00

In my case for that blog:

before

static: 371 items, totalling 30,9 MB

after

static: 371 items, totalling 25,8 MB

First test

> prof_michal.jpg, 21,7 kB (21 711 bytes)
> convert prof_michal.jpg -quality 0 prof_michal.jpg
> prof_michal.jpg, 11,2 kB (11 228 bytes)

Convert all files

#!/usr/bin/env bash

function convert_compress {
    file_extension=$1
    for file in $(find . -type f -name "$file_extension"); do

        file_path=$(basename -- "$file")
        dir=$(dirname "$file")
        file_name="${file_path%.*}"
        extension="${file##*.}"

        old_file_name=${file}
        old_file_name_size=$(stat -c%s "$file")
        new_file_name="$dir/$file_name.jpg"
        convert ${old_file_name} -quality 0 ${new_file_name}
        new_file_name_size=$(stat -c%s "$new_file_name")

        if [[ "$extension" != "jpg" ]]
        then
            rm ${file}
        fi
        echo "$old_file_name | $new_file_name | $old_file_name_size | $new_file_name_size"
    done
}

convert_compress "*.jpg"
convert_compress "*.jpeg"
convert_compress "*.png"