我正在尝试使用Image-Magick和PHP将SVG文本转换为PNG图像。这个SVG是使用NVD3生成的图表,我想让我的用户将其下载为图像。
基本上,我将用JSON编码的SVG数据发送到PHP处理程序,该处理程序应该将其作为PNG图像输出。
但是,这会引发以下错误:
Fatal error: Uncaught exception 'ImagickException' with message 'no decode delegate for this image format `' @ blob.c/BlobToImage/347' in svg2png.php:4 Stack trace: #0 svg2png.php(4): Imagick->readimageblob('
用于转换图像的PHP脚本:
<?php
/* Derived in part from: http://stackoverflow.com/a/4809562/937891 */
$svg=json_decode($_REQUEST["svgData"]);
$im=new Imagick();
$im->readImageBlob($svg);
$im->setImageFormat("png24");
header("Content-Type: image/png");
$thumbnail = $im->getImageBlob();
echo $thumbnail;
?>
HTML:
<form id="exportSpendTrendTrigger" method="POST" action="svg2png.php" target="_blank">
<input id="exportSpendTrendSvgData" type="hidden" name="svgData" />
<input type="submit" class="btn" value="Export" />
</form>
<div id="spendtrend">
<svg></svg>
</div>
jQuery的:
exportSpendTrend = function (e) {
//Show the user the PNG-image version for download
$("#exportSpendTrendSvgData").val( JSON.stringify($("#spendtrend").html().trim()) );
}
$("#exportSpendTrendTrigger").on("submit", exportSpendTrend);
示例SVG,由NVD3生成:http://pastebin.com/Z3TvDK16
这是在使用PHP 5.3和Imagick的Ubuntu服务器上
需要为readImageBlob
指定svg文件文本结构来解码文件。将<?xml version="1.0" encoding="UTF-8" standalone="no"?>
添加到具有svg文本的变量中。
$svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'.$svg;
你很高兴。
记得那个
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
必须是包含SVG文本的变量的第一行。知道这可能会让你有些头疼。