5

In my Ubuntu server, I have a specific directory that contains a large number of images that I wish to resize to a width of 2000px if they are larger than 2000 pixels whilst maintaining their aspect ratio but if an image's width is less than 2000px it shall remain unchanged.

I want to edit the original image and not make a copy and I have no GUI installed on my server.

Sainan
  • 1,274
  • 2
  • 19
  • 32
Adam Scot
  • 1,371
  • 4
  • 21
  • 41

1 Answers1

9

You might want to use ImageMagick. It isn't included in the default installations of Ubuntu and many other Linux distributions, so you will have to install it first. Use the following command:

sudo apt-get install imagemagick

You can specify a width (or height) and ImageMagick will resize the image for you while preserving the aspect ratio.

The following command will resize an image to a width of 2000:

convert example.png -resize 2000 example.png

There is also an option so that it will only shrink images to fit into the given size. It won't enlarge images that are smaller. This is the '>' resize option. Think of it only applying the resize to images 'greater than' the given size, the syntax might be a little counter-intuitive.

convert example.png -resize 2000\>  example.png

You can use bash to apply the command to all of your images,

for file in *.png; do convert $file -resize 2000\> $file; done
Filip Allberg
  • 3,941
  • 3
  • 20
  • 37
  • You will, however, need root access in order to resize an image that is larger than 16000 pixels on a side or 128 MP area because of the `policy.xml` that Ubuntu's ImageMagick package installs. – Damian Yerrick Dec 21 '21 at 21:37
  • Instead of `-resize 2000\>` you can also write `-resize '2000>'`. Documentation see https://legacy.imagemagick.org/script/command-line-processing.php#geometry – PiTheNumber Mar 18 '22 at 14:00