Bash Function to Calculate Image Print Size
This one is pretty niche but I find it handy so thought I'd post it here in case others find it useful.
Often times I find myself needing to calculate the print size of an image, mainly for inclusion in exhibition catalogues. I would usually have to fire up Photoshop or similar which seems long winded, so i wrote a bash function (though these days I use zsh as my terminal). I save this in my list of bash functions so I can trigger like so:
calcImageSize ./image_printres.tiff 300
The first argument is the path to the image and the second argument is the DPI.
Or if I want to write the output to a file:
calcImageSize ./image_printres.tiff 300 > image_printres.txt
I then get output like this:
Image dimensions: 4977x7015 pixels
Physical size at 300 DPI: 421.38 mm x 593.85 mm
Here's the function:
calcImageSize() {
# Parameters: image file path and DPI
local image_path="$1"
local dpi="$2"
# Check if image path and DPI are provided
if [[ -z "$image_path" || -z "$dpi" ]]; then
echo "Usage: calculate_image_size <image_path> <dpi>"
return 1
fi
# Check if ffprobe is installed
if ! command -v ffprobe &> /dev/null; then
echo "ffprobe is not installed or not in PATH."
return 1
fi
# Get image dimensions using ffprobe
local dimensions
dimensions=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 "$image_path")
if [[ $? -ne 0 ]]; then
echo "Error: Could not retrieve image dimensions."
return 1
fi
# Parse width and height
local width=$(echo "$dimensions" | cut -d',' -f1)
local height=$(echo "$dimensions" | cut -d',' -f2)
if [[ -z "$width" || -z "$height" ]]; then
echo "Error: Failed to parse image dimensions."
return 1
fi
# Calculate physical size in mm
local inch_to_mm=25.4
local width_mm
local height_mm
width_mm=$(echo "scale=2; ($width / $dpi) * $inch_to_mm" | bc)
height_mm=$(echo "scale=2; ($height / $dpi) * $inch_to_mm" | bc)
# Output results
echo "Image dimensions: ${width}x${height} pixels"
echo "Physical size at ${dpi} DPI: ${width_mm} mm x ${height_mm} mm"
}