Gmagick convert SVG to PNG with transparent background

1k Views Asked by At

I have a problem converting SVG to PNG. The background is white even tough it should be transparent.

Example code:

$im = new Gmagick();
$im->readImageBlob('<?xml version="1.0"?>'.$svg);
$im->setImageBackgroundColor(new \GmagickPixel('transparent')); 
$im->setimagecolorspace(\Gmagick::COLORSPACE_TRANSPARENT); 
$im->scaleImage(1024,1024,1);
$im->setResolution ("300","300");
$im->setImageFormat('PNG32');
$im->setImageDepth(32);
$im->getImageBlob();

Example SVG:

<svg width="640" height="480">
    <rect height="254" width="459" y="117" x="99" stroke-width="5" stroke="#000000" fill="#FF0000" />
    <rect width="241.35593" height="211.52542" x="387.7966" y="225.08475" />
</svg>

With Graphic Magick directly i have not problem exemple line commande :

gm convert -size 1200x1200 -background none svg.svg svg.png

How can I fix this?


Edit: Currently i use this code

shell_exec("gm convert -resize ".$width."x".$height." -background none svg.svg svg.png");

This works but i hate use shell_exec, it's dirty.

1

There are 1 best solutions below

0
On

A little bit late, but you have to use method "backgroundColor" instead of "imageBackgroundColor" and you have to place before "readImageBlob", not after.

So your code should look like this:

$im = new Gmagick();
$im->setBackgroundColor(new \GmagickPixel('transparent')); 
$im->readImageBlob('<?xml version="1.0"?>'.$svg);
$im->setimagecolorspace(\Gmagick::COLORSPACE_TRANSPARENT); 
$im->scaleImage(1024,1024,1);
$im->setResolution ("300","300");
$im->setImageFormat('PNG32');
$im->setImageDepth(32);
$im->getImageBlob();