Skip to content

Instantly share code, notes, and snippets.

@Sktbanerjee1
Last active April 28, 2024 17:33
Show Gist options
  • Save Sktbanerjee1/c5c8f417eb9ba087ba9317e991a29c31 to your computer and use it in GitHub Desktop.
Save Sktbanerjee1/c5c8f417eb9ba087ba9317e991a29c31 to your computer and use it in GitHub Desktop.
A shell script to batch convert SVG files to PNG using the Inkscape command line

svg2png_batch

A shell script to batch convert SVG images to PNG using the Inksacpe command line.

  • Given a folder containing SVG files, each image is converted to a PNG.
  • Original folder structure is maintained.
  • Supports specification of the output image resolution

Getting started

  • Inkscape nust be installed and availble in the $PATH (check with inkscape --version).
  • Download the script and change modify the permission, so that the file is executable chmod +x svg2png_batch.sh.

Use

# convert the SVG files located in the <inout_folder> to PNG images
#!/bin/bash
./svg2png_batch.sh <input_folder> <output_folder> <resolution>
<input_folder> -- Folder where the SVG files are located
<output_folder> -- Folder where the outputs will be written
<resolution> -- Output image resolution
#!/bin/bash
# Check for correct number of arguments
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <input_folder> <output_folder> <resolution>"
exit 1
fi
INPUT_FOLDER=$1
OUTPUT_FOLDER=$2
RESOLUTION=$3
# Check if the input folder exists
if [ ! -d "$INPUT_FOLDER" ]; then
echo "Error: Input folder does not exist."
exit 1
fi
# Create output folder if it doesn't exist
mkdir -p "$OUTPUT_FOLDER"
# Find all SVG files and store count
SVG_FILES=($(find "$INPUT_FOLDER" -name '*.svg'))
TOTAL_FILES=${#SVG_FILES[@]}
# Check if there are SVG files
if [ $TOTAL_FILES -eq 0 ]; then
echo "No SVG files found in the directory."
exit 1
fi
echo "Starting conversion of $TOTAL_FILES files..."
# Loop over all SVG files and convert them
for ((i=0; i<$TOTAL_FILES; i++)); do
SVG_FILE=${SVG_FILES[$i]}
RELATIVE_PATH="${SVG_FILE#$INPUT_FOLDER}"
PNG_FILE="$OUTPUT_FOLDER/${RELATIVE_PATH%.svg}.png"
# Ensure output directory exists
mkdir -p "$(dirname "$PNG_FILE")"
# Log the folder and file being processed
echo -n "Processing ($((i+1))/$TOTAL_FILES): $SVG_FILE"
# Convert SVG to PNG using Inkscape
inkscape "$SVG_FILE" --export-type=png --export-filename="$PNG_FILE" --export-dpi="$RESOLUTION"
# Simple progress bar
PERCENT=$(( (i + 1) * 100 / TOTAL_FILES ))
printf "\r[%-50s] %d%%" $(printf "#%.0s" $(seq 1 $((PERCENT / 2)))) $PERCENT
echo ""
done
echo "Conversion completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment