Pages

Thursday, 24 March 2022

A simple script to combine every 8 pictures into one for printing

 Yesterday I got asked to help edit around 80 pictures so that every 8 of them are combined into one big picture in the format of 2 rows and 4 columns. Photoshop or Gimp for sure can be used to do this work. But they are not the perfect tools for such "batch" repeated jobs.


Let's do it with ImageMagick!

The important ImageMagick concept I learned from this tiny project is "image set".

- Unlike an image setting, which persists until the command-line terminates,

an operator is applied to the current image set and forgotten

- The current image set includes all images listed before the operator, in the current stack.

- parenthesis () are used to create image stacks.

e.g.

magick input_file1 input_file2 IMAGEOPERATOR1 input_file3 IMAGEOPERATOR2 output_file

IMAGEOPERATOR1 affects image set which includes input_file1 and input_file2.

IMAGEOPERATOR2 affects image set which includes input_file1, input_file2 and input file3.


magick input_file1 \( input_file2 IMAGEOPERATOR1 \) input_file3 IMAGEOPERATOR2 output_file

IMAGEOPERATOR1 affects the image set which includes  input_file2 only.

IMAGEOPERATOR2 affects the image set which includes  input_file1, stack(which includes input_file2), and input_file3.

Source code is attached as below.

$ cat 8to1.sh
#!/bin/bash
# This script is used to combine every 8 pics into one image
# in format of 2 rows and 4 colums.
# If less than 8 pics were given, the builtin image logo: is used as replacements.

function _8to1() {
    if [[ ! -d 8to1 ]]; then
        mkdir 8to1
    fi
    local pics=()
    local i=0
    for i in {1..8}
    do
        pics+=( 'logo:' )
    done
    i=0
    while [[ $# -gt 0 ]]
    do
        pics[i]="$1"
        shift
        ((i++))
    done
    magick convert \
    -bordercolor white \
    \( ${pics[0]} ${pics[1]} ${pics[2]} ${pics[3]} -border 20 -resize 900x1200\! +append \) \
    \( ${pics[4]} ${pics[5]} ${pics[6]} ${pics[7]} -border 20 -resize 900x1200\! +append \) \
    -append \
    ./8to1/$(date +%s%N).jpg
}
########################## main ###################
i=0
pics=()
while [[ $# -gt 0 ]]; do
  pics+=( "$1" )
  shift
  ((i++))
  if [[ $((i % 8)) -eq 0 ]]; then
      _8to1 ${pics[@]}
      pics=()
  fi
done
if [[ ${#pics[@]} -gt 0 ]]; then
      _8to1 ${pics[@]}
fi

No comments:

Post a Comment