将SVG转换为PNG时出现致命错误

将SVG转换为PNG时出现致命错误

本文介绍了readimageblob:将SVG转换为PNG时出现致命错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Image-Magick与PHP结合使用,以将SVG文本转换为PNG图像.此SVG是使用 NVD3 生成的图表,我希望允许我的用户将其下载为图像.

I'm trying to use Image-Magick with PHP to convert SVG text into a PNG image. This SVG is a chart generated with NVD3 and I'd like to allow my users to download it as an image.

基本上,我会将以JSON编码的SVG数据发送到PHP处理程序,该处理程序应该将其输出为PNG图像.

Basically, I'm sending the SVG data, encoded with JSON to the PHP handler which is supposed to output it as a PNG image.

但是,这引发了以下错误:

But, this throws up the following error:

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);

由NVD3生成的

示例SVG : http://pastebin.com/Z3TvDK16

Example SVG, generated by NVD3: http://pastebin.com/Z3TvDK16

这是在装有PHP 5.3和Imagick的Ubuntu服务器上

This is on an Ubuntu server with PHP 5.3 and Imagick

推荐答案

svg文件文本结构需要为readImageBlob指定以解码文件.在具有cvg文本的变量前加上<?xml version="1.0" encoding="UTF-8" standalone="no"?>.

svg file text structure needs to be specified for readImageBlob to decode the file.Prepend <?xml version="1.0" encoding="UTF-8" standalone="no"?> to your variable having svg text.

$svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'.$svg;

你很好.

这篇关于readimageblob:将SVG转换为PNG时出现致命错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 15:21