Skip to content

Instantly share code, notes, and snippets.

@Gosha
Last active August 29, 2015 14:07
Show Gist options
  • Save Gosha/657dc4f0cf0aafc22e30 to your computer and use it in GitHub Desktop.
Save Gosha/657dc4f0cf0aafc22e30 to your computer and use it in GitHub Desktop.
Calculate the aspect ratio of an image
#!/bin/bash
# Called with ./image_ratio.sh IMAGEFILE
# convert is from ImageMagick
image_width () {
convert "$1" -format "%w" info:
}
image_height () {
convert "$1" -format "%h" info:
}
# Stolen (and edited) from http://www.tldp.org/LDP/abs/html/ops.html
gcd () {
local dividend=$1 # Arbitrary assignment.
local divisor=$2 #! It doesn't matter which of the two is larger.
# Why not?
local remainder=1 # If an uninitialized variable is used inside
#+ test brackets, an error message results.
until [ "$remainder" -eq 0 ]
do # ^^^^^^^^^^ Must be previously initialized!
let "remainder = $dividend % $divisor"
dividend=$divisor # Now repeat with 2 smallest numbers.
divisor=$remainder
done # Euclid's algorithm
echo $dividend
}
IMAGE=$1
WIDTH=$(image_width $IMAGE)
HEIGHT=$(image_height $IMAGE)
GCD=$(gcd $WIDTH $HEIGHT)
echo "GCD: $GCD"
let "A = $WIDTH / $GCD"
let "B = $HEIGHT / $GCD"
echo $A:$B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment