10

I want to convert SVG into PNG using ImageMagick using PHP. I have installed ImageMagick on XAMPP and verified it using phpinfo(), but still can't generate 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();
1
  • First it takes too long and next it creates a blank page.
    – Badar
    Commented May 2, 2015 at 7:01

2 Answers 2

1

It may not be related to your problem, but have you tried to call the Imagick class with a "\" before ? Like : $newImage = new \Imagick();

I know that I had the same error as you, that is the class couldnt be found, until I added this prefix namespace. I think its related to namespace and how you load your class files with the classLoader of your web-app.

0

If you get blank png images even though you are following all the advice here, you may want to check that any text within your svg is suitably escaped. I spent an hour or two scratching my head as to why I wasn't getting any output, until I discovered that I had an ampersand in my text. The fix was to pass the text through htmlspecialchars() first, 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 anyone else facing similar problems.

Not the answer you're looking for? Browse other questions tagged or ask your own question.