Cross-browser SVG to PNG. Solution for a tainted canvas in Safari and mobile Chrome.

May 31, 2022 ≈ 51 seconds

How to convert inline SVG image into PNG in the browser? —The easiest way is to draw it on the canvas and use toDataUrl() function. The catch is browser support, especially mobile browsers and desktop Safari. When you try to use toDataUrl() function of canvas with SVG, it becomes «tainted» and blows up with an error. Setting image.crossOrigin wouldn't help.

Nuclear solution? — Server-side SVG to PNG conversion for unsupported browsers! Easiest solution with php is to use ext-imagick:

That solution would do the job, but sometimes it wouldn't render complex SVG's or would render with artefacts.

What would be faster than headless Chrome and wouldn't require node? — Inkscape!

sudo apt-get install Inkscape

If you use the latest versions of Inkscape and Imagemagick, Imagemagick solution should work out of the box after you install the Inkscape. But if it's not, you can use Inkscape directly through the command line:


use Symfony\Component\Process\Process;

$svg_file = '<svg>...</svg>';
$process = new Process(['inkscape', '--pipe', '--export-type', 'png', '--export-filename', '-']);
$image = $process->getOutput();

Subscribe to our newsletter

If you provide url of your website, we send you free design concept of one element (by our choice)

Subscribing to our newsletter, you comply with subscription terms and Privacy Policy