Batch resizing images using the command line in Ubuntu and ImageMagick

Large images means large page size, which means slow WordPress and page load times for users. The most common reason is image size or lack of compression. If you’ve never had any image size restrictions or auto-resizing on your site, it can be very handy to batch resize those images in Linux.

This tutorial will show you how to resize a group of JPG and PNG files using ImageMagick on Ubuntu or Debian.

Batch resizing images using Linux command line and ImageMagick

First, we have to install ImageMagick from the repository on Debian or Ubuntu.

sudo apt-get update
sudo apt-get install imagemagick -y

it’s better to use identify to get the height

identify -format "%wx%h" image.jpg

You will see the resolution: width and then height.


You can resize the image if it is large and you can specify dimensions. This will automatically preserve the aspect ratio of the image.

Note: The program overwrites the original image!

convert image.jpg -resize 1040x880> image.jpg

Check the resized image

identify -format "%wx%h" image.jpg

Things are good!


We can now move on to batch resizing

Batch resizing images with Linux and Imagemagick

Create the following script

mkdir -p ~/scripts
nano ~/scripts/

Paste the script below.

FOLDER this is the absolute path to your images folder

WIDTH – maximum width and HEIGHT Is the maximum height.

It will overwrite your original images, make sure you have a backup before launch!

#!/usr/bin/env bash
# Purpose: Пакетное измененние размера файлов
# Source:
# Author: andreyex

# абсолютный путь к папке с изображениями

# высота изображения

# ширина изображения

# размер по высоте или ширине, держим пропорции, используя imagemagick
find $FOLDER -iname '*.jpg' -o -iname '*.png' -exec convert {} -resize $WIDTHx$HEIGHT> {} ;

Press Ctrl + X, Y and Enter to save and exit.

Check folder size

du -sh foldername

Check the final size


The screen command will make the batch conversion work even if your SSH session ends.

sudo apt-get install screen

Create a new session screen, press space or type screen


Execute the script

bash ~/scripts/

Detach the screen with Ctrl + A and then press D (remove).

You can use top command and watch processes jpegoptim at the same time.


screen -r

Check the folder size again

du -sh foldername

You should see improvement


Make sure to compress your images with Lossless or Lossy Compression (current guide).

If you need to do some more advanced commands, use a regular expression, this should help