How to convert SVG to PNG using ImageMagick in PHP?
I want to convert SVG to PNG using ImageMagick using PHP. I installed ImageMagick on XAMPP and tested it with phpinfo () but still can't create images. Here is my code:
$svg = file_get_contents($svg_file);
//echo $svg;
$im = new Imagick();
//$im->setBackgroundColor(new ImagickPixel('transparent'));
// $svg = str_replace(array("color1","color2"),array("red","lightblue"),$svg);
$im->readImageBlob($svg);
//$im->setImageFormat("png32");
$im->setImageFormat("png24");
// $im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1);
// $im->adaptiveResizeImage(720, 445);
$im->writeImage($png_file);
header('Content-type: image/png');
echo $im;
$im->clear();
$im->destroy();
source to share
Read this Imagick for Windows 8 xampp
I am making this example and it works for me, just download blank-us-map.svg
<?php
$usmap = 'blank-us-map.svg';
$im = new Imagick();
$svg = file_get_contents($usmap);
$im->readImageBlob($svg);
$im->setImageFormat("png24");
$im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1); /*Optional, if you need to resize*/
$im->writeImage('blank-us-map.png');
header('Content-type: image/png');
echo $im;
$im->clear();
$im->destroy();
?>
source to share
This may not be related to your problem, but have you tried calling the Imagick class with "\" before? Like: $ newImage = new \ Imagick ();
I know I had the same error as you, this could not be found in the class until I add this prefix namespace. I think it has to do with namespace and how you load your class files using the classLoader of your web application.
source to share
If you are getting empty png images, even if you follow all the guidelines here, you can check that any text in your svg is escaped appropriately. I spent an hour or two scratching my head about why I wasn't getting any results until I found I had an ampersand in my text. The fix was to first pass the text through htmlspecialchars () i.e.
$annotation = htmlspecialchars($this->sequence . ' : ' . $this->name);
$svg .= "<text id=\"annotation-{$this->index}\" x=\"{$this->xText}\" y=\"{$this->yText}\" font-size=\"12\" style=\"fill: #000000\" onclick=\"passClickToTask(evt)\"> $annotation</text>";
Hope this helps someone else with similar problems.
source to share