SVGs to PNGs (with transparency) using PHPs Imagemagick library

While working on a project for work, it became necessary to generate a series of images which would be stamped onto a PDF page.

Our php/pdf solution only supports raster images (JPEGs/PNGs etc) while our stamps were SVGs. This handy snippet of code converts an SVG into a PNG using imagemagick but with a transparent background colour.

<?php
$im = new Imagick();
$im->setBackgroundColor(new ImagickPixel('transparent'));
$svg = file_get_contents("path/to/svg.svg");
$im->readImageBlob($svg);
$im->setImageFormat("png32");
$im->imageWriteFile("path/to/save/svg.png");

Ben Squire

Read more posts by this author.

Leicestershire, United Kingdom https://squired.co.uk