💊 Resize an image to fit size

2021.5.5

It is the case than I often need to resize a bunch of PNGs of random sizes to a maximum height of 350px, preserving ratio.

Many people would use some many-MB-weighted GUI bloatware and multiple mouse clicks to achieve that (expecially on w1nd0w5). Computer users who love computers choose the CLI way.


ImageMagick is the solution, and is likely to be packaged for your OS.
Once installed, you can run convert from the shell.

Now to resize 1.png to fit the desired size you can do:

$ file 1.png         
1.png: PNG image data, 2119 x 1056, 8-bit/color RGB, non-interlaced
$ convert 1.png -resize 350x350 1-350.png        
$ file 1-350.png                         
1-350.png: PNG image data, 350 x 174, 8-bit/color RGB, non-interlaced

This is already amazing, but I need the image height to be 350px.
To do that, you specify only the height.

$ convert 1.png -resize x350 1-350.png 
$ file 1-350.png                      
1-350.png: PNG image data, 702 x 350, 8-bit/color RGB, non-interlaced

Great! Now I need to do the same thing for every image in this directory. Let’s find them.

$ ls   
1.png  2.png  3.png  4.png
$ mkdir ../out      
$ find . -type f -exec convert {} -resize x350 ../out/{} \;
$ file ../out/*                                            
../out/1.png: PNG image data, 239 x 350, 8-bit/color RGB, non-interlaced
../out/2.png: PNG image data, 178 x 350, 8-bit/color RGB, non-interlaced
../out/3.png: PNG image data, 632 x 350, 8-bit/color RGB, non-interlaced
../out/4.png: PNG image data, 204 x 350, 8-bit/color RGB, non-interlaced

Nice.