Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert SVG to PNG using ImageMagick in PHP?

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();
like image 683
Badar Avatar asked May 01 '15 20:05

Badar


2 Answers

Read this Imagick on Windows 8 xampp

I make this example and works for me, just download the 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();

?>
like image 99
Adrian Cid Almaguer Avatar answered Oct 01 '22 18:10

Adrian Cid Almaguer


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.

like image 28
Franz Avatar answered Nov 09 '22 07:11

Franz