Last active
April 4, 2023 12:10
-
-
Save oliver-la/43c01da34a735d6e62e4c8425836115d to your computer and use it in GitHub Desktop.
Bash Script to convert irregulary sized SVGs (different aspect ratio and sizes each) into 1:1 aspect ratio while also centering its contents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
INPUT="$1" | |
SIZE=$2 | |
OUTPUT="$3" | |
INKSCAPE="${INKSCAPE:-/Applications/Inkscape.app/Contents/MacOS/inkscape}" | |
if [ -z "$INPUT" ] || [ -z "$SIZE" ] || [ -z "$OUTPUT" ]; then | |
echo "Usage: $0 [input] [size] [output]" | |
exit 1 | |
fi | |
# Get dimensions of the entire svg document, ignore children as we'll resize everything at once later | |
bounding_boxes=`$INKSCAPE $1 -S | head -n1` | |
# element_name,x,y,width,height | |
original_width=$(echo $bounding_boxes | cut -d ',' -f4) | |
original_height=$(echo $bounding_boxes | cut -d ',' -f5) | |
WIDTH_MULTIPLICATOR=$(echo "scale=3; $original_width / $SIZE" | bc) | |
HEIGHT_MULTIPLICATOR=$(echo "scale=3; $original_height / $SIZE" | bc) | |
OFFSET_X=0 | |
OFFSET_Y=0 | |
if (( $(echo "scale=3; $original_height > $original_width" |bc -l) )); then | |
OFFSET_X=$(echo "scale=3; ($SIZE - ($original_width / $HEIGHT_MULTIPLICATOR)) / 2" | bc) | |
else | |
OFFSET_Y=$(echo "scale=3; ($SIZE - ($original_height / $WIDTH_MULTIPLICATOR)) / 2" | bc) | |
fi | |
# Handle edge cases where a negative offset may occur, rsvg-convert can't handle negative values and will print | |
# "Found argument '-.' which wasn't expected, or isn't valid in this context" | |
if [[ "$OFFSET_X" == -* ]]; then | |
OFFSET_X=0 | |
fi | |
if [[ "$OFFSET_Y" == -* ]]; then | |
OFFSET_Y=0 | |
fi | |
rsvg-convert -a -f svg --page-height "$SIZE" --page-width "$SIZE" -w "$SIZE" -h "$SIZE" --left "$OFFSET_X" --top "$OFFSET_Y" "$INPUT" > "$OUTPUT" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To batch-process files in the current directory, and output them to ../fixed (must exist!)
for file in *.svg; do; ../conv-svg.sh "$file" 40 "../fixed/$file"; done