Skip to content

Instantly share code, notes, and snippets.

@borisschapira
Created November 21, 2024 18:06
Show Gist options
  • Save borisschapira/ae5819c0f2d7df66d480605740cc1f0a to your computer and use it in GitHub Desktop.
Save borisschapira/ae5819c0f2d7df66d480605740cc1f0a to your computer and use it in GitHub Desktop.
Shell script to transform a folder of square-viewbox SVGs in 1024x1024 PNGs, changing the "currentColor" stroke color along the way
#!/bin/bash
# Prerequisites:
# - macOS (for the sed syntax with -i '')
# - inkscape is installed
# - usage: INKSCAPE_PATH=/Applications/Inkscape.app/Contents/MacOS/inkscape ~/svgToPng.sh ./SVG '#7c0033' 'BURGUNDY'
# Function to check if a string is a valid hexadecimal RGB color
is_valid_hex_rgb() {
local hex_color=$1
if [[ $hex_color =~ ^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$ ]]; then
return 0
else
return 1
fi
}
# Check if exactly three parameters are provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <folder_name> <color_hex> <color_name>"
exit 1
fi
# Assign parameters to variables
folder_name=$1
color_hex=$2
color_name=$3
# Check if folder name is an actual folder
if [ ! -d "$folder_name" ]; then
echo "Error: $folder_name is not a valid directory."
exit 1
fi
# Check if color_hex is a valid hexadecimal RGB color
if ! is_valid_hex_rgb "$color_hex"; then
echo "Error: $color_hex is not a valid hexadecimal RGB color. Format should be #RGB or #RRGGBB."
exit 1
fi
# Check if color_name is a non-empty string
if [ -z "$color_name" ]; then
echo "Error: Color name cannot be empty."
exit 1
fi
# Check if INKSCAPE_PATH environment variable is set
if [ -z "$INKSCAPE_PATH" ]; then
# If not set, check if inkscape is in the PATH
if ! command -v inkscape &> /dev/null; then
echo "Error: inkscape command not found. Please ensure inkscape is installed and in your PATH, or set the INKSCAPE_PATH environment variable."
exit 1
fi
INKSCAPE_PATH="inkscape"
fi
# Echo the parameters
echo "Folder Name: $folder_name"
echo "Color Hex: $color_hex"
echo "Color Name: $color_name"
# Create a new folder as a copy of the folder provided in the folder_name param
cp -r "$folder_name" "$color_name"
# Inside this copied folder, find all SVG files and replace the string currentColor with the color_hex
find "$color_name" -type f -name "*.svg" -exec sed -i "" "s/currentColor/$color_hex/g" {} \;
# Use inkscape to convert all SVG files to 1024px by 1024px PNGs
for svg_file in "$color_name"/*.svg; do
if [ -f "$svg_file" ]; then
"$INKSCAPE_PATH" "$svg_file" --export-type=png --export-filename="${svg_file%.svg}.png" --export-width=1024 --export-height=1024
rm "$svg_file"
fi
done
echo "Processing complete. SVG files have been converted to PNGs in the folder: $color_name"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment