Batch converting SVG to PNG in Inkscape doesn't work

Viewed 1743

I want to convert multiple SVG files in the folder C:\Users\Eric\Desktop\svg to 512x512 PNG files with the name [SVG File Name].svg.png.

I tried the following command: for /f %f in ('dir /b "C:\Users\Eric\Desktop\svg"') do inkscape -z -e %f.png -w 512 -h 512 %f

The command line detects the SVG files correctly and goes through them but Inkscape says the following:

C:\Users\Eric\Desktop\inkscape>inkscape -z -e [SVG File Name].svg.png -w 512 -h 512 [SVG File Name].svg

** (inkscape.exe:8412): WARNING **: Can't open file: [SVG File Name].svg (doesn't exist)

** (inkscape.exe:8412): WARNING **: Can't open file: [SVG File Name].svg (doesn't exist)

** (inkscape.exe:8412): WARNING **: Specified document [SVG File Name].svg cannot be opened (does not exist or not a valid SVG file)

I opened one file in the normal Inkscape program, and it worked.

2 Answers

For SVG to PNG conversion I found cairosvg (https://cairosvg.org/) performs better than ImageMagick. Steps for install and running on all files in your directory.

pip3 install cairosvg

Open a python shell in the directory which contains your .svg files and run:

import os
import cairosvg

for file in os.listdir('.'):
    if os.path.isfile(file) and file.endswith(".svg"):
        name = file.split('.svg')[0]
        cairosvg.svg2png(url=name+'.svg',write_to=name+'.png')

This will also ensure you don't overwrite your original .svg files, but will keep the same name. You can then move all your .png files to another directory with:

$ mv *.png [new directory]

Inkscape is a good program. Sometimes we don't understand the possibilities it has. For better performance, you should use shell mode. This mode consists of 2 steps:

  1. Create a file, with the commands to execute.
  2. Run this file using type .\command.txt | inkscape --shell where command.txt your file name, in windows console or bash.

All commands located in action-list, after typing inkscape --shell.

For example, if you want to convert SVG to png, your txt file should contains:

file-open:1.svg; export-filename:1.png; export-do; file-close
file-open:2.svg; export-filename:2.png; export-do; file-close

Syntax is command:arg; command2:arg2; etc

You can create this file using your favorite language like C++, Java, C# or Python.

P.S.

It's faster than using inkscape command with every file in PowerShell, but don't use it for long time operations because it has a memory leak: Link to Gitlab

Related