Skip to content

Instantly share code, notes, and snippets.

@luismrsilva
Last active November 4, 2023 20:24
Show Gist options
  • Save luismrsilva/9e6401c12912c822dfc484d28125963b to your computer and use it in GitHub Desktop.
Save luismrsilva/9e6401c12912c822dfc484d28125963b to your computer and use it in GitHub Desktop.
Overlay logo over image, resizing logo to x% of the smallest dimension of the image
#!/bin/bash
# Author: https://github.com/luismrsilva
# (c) 2019 luismrsilva
# Config
## percent of smaller dimension of image
## this size will be used on the largest side of the logo
LOGO_PERCENT=25
LOGO_OFFSET_PERCENT=3
# as per ImageMagic -gravity
# $ convert -list gravity
GRAVITY=southeast
######
if [ "$#" -lt 3 ]; then
echo "Overlay logo over image, resizing logo to x% of the smallest dimension of the image"
echo "Usage: $0 <logo> <out_dir> <img> [logo_gravity] [list-file]"
echo
echo " [list-file] file where to append a line with img and gravity"
exit 1
fi
if [ "$#" -gt 3 ]; then
GRAVITY="$4"
fi
if [ "$#" -gt 4 ]; then
LIST_FILE="$5"
fi
LOGO=$1
OUT_DIR=$2
IMG=$3
# echo "LOGO: $LOGO" >&2
# echo "OUT_DIR: $OUT_DIR" >&2
# echo "IMG: $IMG" >&2
function getImgDim(){
identify -format '%wx%h' "$1"
}
function getDimW(){
echo "$1" | cut -d "x" -f1
}
function getDimH(){
echo "$1" | cut -d "x" -f2
}
LOGO_DIM=$(getImgDim $LOGO)
LOGO_DIM_W=$(getDimW $LOGO_DIM)
LOGO_DIM_H=$(getDimH $LOGO_DIM)
IMG_DIM=$(getImgDim $IMG)
IMG_DIM_W=$(getDimW $IMG_DIM)
IMG_DIM_H=$(getDimH $IMG_DIM)
# echo Logo: ${LOGO_DIM_W}x${LOGO_DIM_H}
# echo IMG: ${IMG_DIM_W}x${IMG_DIM_H}
# get min(w, h)
if [ "$IMG_DIM_W" -gt "$IMG_DIM_H" ]; then
IMG_MIN_DIM=$IMG_DIM_H
else
IMG_MIN_DIM=$IMG_DIM_W
fi
LOGO_OUT_DIM=$((LOGO_PERCENT*IMG_MIN_DIM/100))
LOGO_OUT_OFFSET=$((LOGO_OFFSET_PERCENT*IMG_MIN_DIM/100))
# echo "LOGO_OUT_DIM=$LOGO_OUT_DIM"
# echo "LOGO_OUT_OFFSET=$LOGO_OUT_OFFSET"
# echo "GRAVITY=$GRAVITY"
BASENAME=$(basename "$IMG")
echo "BASENAME: $BASENAME"
OUT=$(echo $OUT_DIR/$BASENAME)
echo "Out: $OUT"
# note: the -resize option resizes the image to fit inside a rectangle, preserving AR.
mkdir -p "$OUT_DIR"
convert "$IMG" -auto-level -auto-orient \( "$LOGO" -resize ${LOGO_OUT_DIM}x${LOGO_OUT_DIM} \) -gravity $GRAVITY -geometry +$LOGO_OUT_OFFSET+$LOGO_OUT_OFFSET -composite $OUT
if [ "$?" -eq "0" ] && ! [ "$LIST_FILE" == "" ]; then
echo "$IMG $GRAVITY" | tee -a "$LIST_FILE"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment