SVG to PNG conversion transparent background

IMagick is a native PHP extension to create and modify images using the ImageMagick API. ImageMagick Studio LLC did not write nor does it maintain the IMagick extension, however, IMagick users are welcome to discuss the extension here.
Post Reply
adrianj

SVG to PNG conversion transparent background

Post by adrianj »

Would really appreciate some help on this one please. I think should work, but I am still getting a white background.

Code: Select all

$imagickImage = new Imagick();
$imagickImage->readImage($path_to_svg);  
$imagickImage->setImageBackgroundColor(new ImagickPixel("transparent"));
$imagickImage->setImageFormat("png32");		
$imagickImage->writeImage($path_to_png);
$imagickImage->clear();
$imagickImage->destroy();
I have tested the following which creates a new image and it works fine, so it has something to do with creating a new image versus reading in an SVG, but I can't figure out what.

Code: Select all

$imagickImage = new Imagick();
$imagickImage->newImage(100, 100, new ImagickPixel("orange"));
$imagickImage->setImageBackgroundColor(new ImagickPixel("transparent"));
$imagickImage->waveImage(15, 200);
$imagickImage->trimImage(0);
$imagickImage->setImageFormat("png32");
$imagickImage->writeImage($path_to_png);
$imagickImage->clear();
$imagickImage->destroy();
Thanks for any ideas,
Adrian
adrianj

Re: SVG to PNG conversion transparent background

Post by adrianj »

Surely someone must have done this at some point.

Would really appreciate any thoughts.

Thanks,
Adrian
User avatar
magick
Site Admin
Posts: 11064
Joined: 2003-05-31T11:32:55-07:00

Re: SVG to PNG conversion transparent background

Post by magick »

We wrote the MagickCore / MagickWand API and have not used Imagick. However, if Imagick has analogs to the MagickCore / MagickWand API, it would have a setBackgroundColor() method which you should insert just before the ReadImage() method. Also remove the call to setImageBackgroundColor().
adrianj

Re: SVG to PNG conversion transparent background

Post by adrianj »

magick,

Thank you, that worked perfectly.

For those interested in where I went wrong. I had tried the following after the call to ReadImage().

Code: Select all

$imagickImage->setBackgroundColor(new ImagickPixel("transparent"));
I had also tried putting the following before the call to Readimage() which resulted in an error because the image didn't exist yet.

Code: Select all

$imagickImage->setImageBackgroundColor(new ImagickPixel("transparent"));
I never quite understood that I should/could set the background color of the "canvas"? before reading the image.

Thanks so much,
Adrian
Post Reply