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:
<?php use Symfony\Component\Process\Process; $svg_file = '<svg>...</svg>'; $process = new Process(['inkscape', '--pipe', '--export-type', 'png', '--export-filename', '-']); $process->setInput($svg_file); $process->run(); $image = $process->getOutput();
You didn't provide any data, entered invalid email or already subscribed.
Try again. And if you still can't subscribe—write us.
Address successfully subscribed!