Manipulate Images from Linux Terminal

One of the simplest ways to modify images from terminal in Linux is with ImageMagick utilities. To install ImageMagick on debian/ubuntu, run sudo apt-get install imagemagick.

ImageMagick tool can perform many operations on images. Here we will go over just a few:

Converting image format

One of the simplest things you can do with images is convert the format. Here we will modify a PNG image to a JPG.

# PNG file we are operating on
$ file a.png
a.png: PNG image data, 553 x 302, 8-bit/color RGBA, non-interlaced
# command to convert from PNG to JPG
$ convert a.png b.jpg
# output JPG file
$ file b.jpg
b.jpg: JPEG image data, JFIF standard 1.01, resolution (DPCM), density 38x38, segment length 16, baseline, precision 8, 553x302, frames 3

Resizing

There are multiple ways to resize an image with ImageMagick like increase the image size by hight while keeping aspect ratio. One of the simplest ways is to pass a -resize flag with the new dimension.

# file we are operating on
$ file a.png
a.png: PNG image data, 553 x 302, 8-bit/color RGBA, non-interlaced
# command to resize
$ convert a.png -resize 1106x604 b.png
# resized image
$ file b.png
b.png: PNG image data, 1106 x 604, 8-bit/color RGBA, non-interlaced

Rotating

To rotate an image by some degree, just pass the value with the -rotate option.

# rotate image a.png 180 degrees and save the modified image as b.png
$ convert a.png -rotate 180 b.png

Chaining multiple operations

convert command can accept multiple operations at a time so we could convert image format, resize and rotate an image all in one command.

# original a.png file
$ file a.png
a.png: PNG image data, 553 x 302, 8-bit/color RGBA, non-interlaced
# all three commands chained
$ convert a.png -resize 1106x604 -rotate 180 b.jpg
# output file that is rotated 180 degrees, resized and converted to jpg
$ file b.jpg
b.jpg: JPEG image data, JFIF standard 1.01, resolution (DPCM), density 38x38, segment length 16, baseline, precision 8, 1106x604, frames 3

Notes:

  • If the input file and output files are named the same, then the original file will be overwritten.
  • Since we are working with Linux Terminal, convert utility can be used recursively on multiple images by going over images using a for loop.