Takichiii
Takichiii

Reputation: 563

bash adjusting image dimensions to fit a certain size

I searched everywhere but couldn't find an answer to this. I would like to output all images of a folder in 50Kb exactly and maintain the original aspect ratio.

I tried ImageMagick and resizing to 250x250 e.g but it is not working for me, what it does is change the first dimension and adapt the other, so output images have not the same size.

for image in `ls $@*.jpg`; do
  mogrify "${image}" -resize 250x250 "${image}"
done

How do it? Thanks

Upvotes: 2

Views: 757

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 208013

Updated Answer

If you want the file size of the images to be limited to 50kB, use:

convert input.jpg -define jpeg:extent=50KB output.jpg

Original Answer

Use mogrify, but be careful it will overwrite all your images:

mogrify -resize 250x250! *.jpg

In general, when using mogrify I like to use the -path option to specify an output directory for results, like this to avoid originals getting overwritten:

mkdir results
mogrify -path results ...

Your script will work if you add the ! after the resize which forces the resize even if it distorts the shape of the picture.


If you want a way to do something similar with Python, I wrote an answer that works pretty well here. It does a binary search for a JPEG quality that satisfies a maximum size requirement.

Upvotes: 3

Related Questions