Compress or Resize images in BASH

sudo apt-get install imagemagick
if [ ! -d ./output ]; 
  mkdir output
for item in *.jpeg;
  echo "Converting ${item%.jpeg}"
  convert ${item} -resize 1024 ${item%.jpeg}.png 5

see more options:

Resize image to minimal rate

How about using ImageMagick's convertwhich has exactly such a minimal size option, see Image Geometry options?!

Copy & Paste snippet (bash syntax) – please notice the ^ after the size specification:

for file in *.jpg; do
   echo -n Converting ${file}...
   convert -resize 180x180^ "$file" "th_$file"
   echo done

In addition, if you want to crop the resulting file to a quadratic shape around the center, you can use this script. The SIZE parameter in the first line specifies (surprise, surprise) the final size of the thumbnail.

for file in *.jpg; do
   echo -n Converting ${file}...
   convert -resize ${SIZE}x${SIZE}^ "$file" temp.png
   convert -crop $(identify temp.png | awk -F'[ x]' -v SIZE=$SIZE '{ printf "%ux%u+%u+%u", SIZE, SIZE, ($3-SIZE)/2, ($4-SIZE)/2 }') temp.png "th_$file"
   echo done
rm temp.png

The script is not very optimized, as it runs two commands (identify and convert -crop) on the thumbnail. But as the thumbnail is only small, I think the speed is reasonable.


howto/compress_or_resize_images_in_bash.txt · Last modified: 2022/01/03 16:03 by
Back to top
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0