Skip to content

Instantly share code, notes, and snippets.

@devlifeX
Created January 8, 2022 19:14
Show Gist options
  • Save devlifeX/7c3e24fa47966ec37089f43d03c1fb7b to your computer and use it in GitHub Desktop.
Save devlifeX/7c3e24fa47966ec37089f43d03c1fb7b to your computer and use it in GitHub Desktop.
Install imagemagick. then run this script to find jpg files recursively and compress them. of course you can adjust convert quality or etc.
#!/bin/bash
# You need to install `imagemagick`
# sudo apt install imagemagick
function compress_image {
cd "$1"
HAS_IMAGE=$(ls | grep ".jpg" | wc -l)
if [ "$HAS_IMAGE" -gt 0 ]; then
mkdir -p compress
for i in *.jpg; do
convert -sampling-factor 4:2:0 -strip -quality 60 -interlace JPEG -colorspace sRGB "$i" "${i%.*}-compress.jpg"
mv "${i%.*}-compress.jpg" compress/
done
fi
}
function traverse_dir {
find "$1" -not -path "./compress/*" -type d -exec ls -d {} \; | while read x; do
compress_image "$x"
echo "Compressing Images ----> $x"
done
}
function main() {
traverse_dir "$1"
}
main $(realpath $1)
# sudo chmox +x ./compress_image_recursive.sh
# ./compress_image_recursive.sh ./images
@devlifeX
Copy link
Author

devlifeX commented Jan 8, 2022

Iterate Directory recursively and compress jpg images by ImageMagick.
create compress folder inside of each and put an optimized version in there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment