Skip to content

Instantly share code, notes, and snippets.

@varunchandak
Created October 20, 2023 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varunchandak/2a488e66e6a5869e4611c955f8b366c4 to your computer and use it in GitHub Desktop.
Save varunchandak/2a488e66e6a5869e4611c955f8b366c4 to your computer and use it in GitHub Desktop.
A Bash script to convert an image to a square by adding equal padding to its shorter dimension using ImageMagick.

Image Square Padding Script

This script takes an image as input and converts it into a square by adding equal padding to its shorter dimension. It utilizes ImageMagick for image processing.

Usage

./make_square.sh [input_image] [output_image]

Requirements

  • ImageMagick

Example

./make_square.sh input.jpg output.jpg

This will take input.jpg, add necessary padding to make it square, and save the result as output.jpg.

#!/bin/bash
# Input image
IMAGE="$1"
# Output image
OUTPUT="$2"
# Get width and height of the image
WIDTH=$(identify -format "%w" "$IMAGE")
HEIGHT=$(identify -format "%h" "$IMAGE")
# Calculate padding to be added to make the image square
if [ "$WIDTH" -gt "$HEIGHT" ]; then
PAD=$(( (WIDTH-HEIGHT) / 2 ))
# Check for an odd difference and adjust padding
EXTRA_PAD=$(( (WIDTH-HEIGHT) % 2 ))
convert "$IMAGE" -gravity center -background white -extent ${WIDTH}x$((HEIGHT+PAD*2+EXTRA_PAD)) "$OUTPUT"
else
PAD=$(( (HEIGHT-WIDTH) / 2 ))
# Check for an odd difference and adjust padding
EXTRA_PAD=$(( (HEIGHT-WIDTH) % 2 ))
convert "$IMAGE" -gravity center -background white -extent $((WIDTH+PAD*2+EXTRA_PAD))x${HEIGHT} "$OUTPUT"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment