2012-10-29 53 views
9

當我試圖使用圖像 - Magick用PHP SVG的文本轉換成PNG圖像。這SVG是NVD3生成的圖表,我想,讓我的用戶下載其作爲圖像。readimageblob:致命錯誤轉換成SVG PNG

基本上,我發送SVG數據,使用JSON編碼爲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服務器上

+3

最有可能你的Imagick安裝缺少正確的代表。參見[ImageMagick的SVG轉換爲PNG不是RSVG工作啓動(http://stackoverflow.com/q/11592085) –

回答

22

SVG文件的文本結構需要爲readImageBlob被指定解碼文件。 前置<?xml version="1.0" encoding="UTF-8" standalone="no"?>到您的變量有SVG的文本。

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

你很好去。

5

記住,

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 

必須在包含SVG的文本變量中的第一道防線。知道這可以爲你節省一些頭痛。