Processing a Number of Image Files

This is, again, is mostly a note to my future self. 🙂

Occasionally, I need to process a bunch of image files in a batch. Most often it’s about resizing them, so they fit into a given format of at most xy pixels, or precisely into, say a square format. Here’s how I do it using ImageMagick and a bit of Ruby code:

Processing a single file

ImageMagick comes with convert (it’s linked to …/bin/magick on my machine), as command line tool for processing image files in a whole lot of ways. In order to resize a single file so that it ends up as a square image in a given number of pixels one can use the following on the command line (I use zsh on macOS):

convert input_file.jpg -resize 1200x1200 -background White -gravity center -extent 1200x1200 output_file.jpg

This command

  • reads ‘input_file.jpg’,
  • creates a new image with 1200⨉1200 pixels,
  • a white background,
  • resizes the input image as needed,
  • puts it in the center of the new image
  • and saves it as ‘output_file.jpg’.

Batch processing files

For this step, I use a Ruby script (of course this can also be done in zsh, bash, Python etc.):

images = Dir['file_pattern*.jpg']
images.each do |fn|
  `convert #{fn} -resize 1200x1200 -background White -gravity center -extent 1200x1200  #{fn.gsub(/\./, '_res.')}`

Tip: Be sure to use different names for the input and output file names.


%d bloggers like this: