4

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.

S8N
  • 147
  • 7
  • I have no experience with Gmagick extension but in ImagickPixel you need to specify the image to be transcparent like new ImagickPixel('transparent'), in you case you are creating a non transparent image in $im = new Gmagick(); – KiKMak Feb 17 '17 at 08:42
  • Thx for response but i can use only Gmagick – S8N Feb 17 '17 at 12:27

1 Answers1

0

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();