Code Review Videos > Linux > [Ubuntu] Batch Resize Images and Maintain Aspect Ratio

[Ubuntu] Batch Resize Images and Maintain Aspect Ratio

Today I needed to resize a ton of stock photos in various sizes so that the result was each image was at most 800 pixels in width, but I wanted to maintain the aspect ratio.

What I mean is that if the original image was 8256 x 5504 pixels (where that is width x height), I wanted the resulting image to be 800×533.

The formula for this is:

(5504 / 8256) * 800 = ~533

All well and good for images where the width is wider than the height. But this was a directory full of all sorts of image shapes.

Take another example: I have an image where the dimensions are 2592 x 3872 pixels. This would be an image where the height is greater than the width.

After resizing I wanted this to be 800×1195.

The formula for this is:

(3872 / 2592) * 800 = ~1195

So depending on whether image is wider or taller, I needed to change the formula.

Or did I?

The Computer Does All The Work Solution

I don’t know about you, but maths is not my strong point.

In fact I will do quite a lot to avoid having to work out maths questions.

Fortunately, some clever boffins have already solved the problem above. And very neatly, too.

It’s possible to batch resize entire directories full of images using the mogrify command.

The mogrify command comes via imagemagick, so install that if you haven’t already done so:

sudo apt-get install imagemagickCode language: Shell Session (shell)

OK, now very important, take a back up of your images.

No.

Seriously.

Take a back up of your images.

I’m going to assume you have done that.

OK, so now you have a big directory of large files, kinda like this:

images before batch resizing on ubuntu

Those large file sizes are absolutely killer.

At most I needed all of them to be 800 pixels wide.

Now open up a terminal in that current directory.

The command is ridiculously easy:

mogrify -resize 800x *.jpgCode language: Shell Session (shell)

This command will resize all JPEG images in the current directory to have a width of 800 pixels while automatically adjusting the height to maintain the original aspect ratio.

It might take a while to process. It depends on how many images you have, and how fast your processor is, amongst other things.

Here’s the output for me:

ubuntu after batch resizing

And that’s really all there is to it.

A ton of time saved.

And no need for Photoshop.

By the way, if you haven’t already, try Photopea.com which is basically almost everything you would need from Photoshop, but directly in your browser. Amazing.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.