简体   繁体   English

如何在PHP中使用ImageMagick将SVG转换为PNG?

[英]How to convert SVG to PNG using ImageMagick in PHP?

I want to convert SVG into PNG using ImageMagick using PHP. 我想使用PHP使用ImageMagick将SVG转换为PNG。 I have installed ImageMagick on XAMPP and verified it using phpinfo(), but still can't generate images. 我在XAMPP上安装了ImageMagick并使用phpinfo()进行了验证,但仍然无法生成图像。 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();

Read this Imagick on Windows 8 xampp 在Windows 8 xampp上阅读此Imagick

I make this example and works for me, just download the blank-us-map.svg 我做这个例子并且适合我,只需下载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();

?>

It may not be related to your problem, but have you tried to call the Imagick class with a "\\" before ? 它可能与您的问题无关,但是您之前尝试使用“\\”调用Imagick类吗? Like : $newImage = new \\Imagick(); 喜欢:$ 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. 我认为它与命名空间以及如何使用web-app的classLoader加载类文件有关。

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. 即使您在此处遵循所有建议,如果您获得空白的png图像,您可能需要检查svg中的任何文本是否被适当地转义。 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, ie 修复是首先通过htmlspecialchars()传递文本,即

$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. 希望这能帮助其他遇到类似问题的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM