使用ImageMagic将SVG转换为PNG会忽略填充模式URL

时间:2016-03-01 12:50:47

标签: php svg imagick imagemagick-convert

我正在使用PHP的Imagick类将SVG转换为PNG。

转换成功但似乎忽略了任何填充模式。这是我的代码:

<?php

$svg = <<<SVG
<?xml version="1.0"?>
<svg>
    <defs>
        <pattern id="myPattern" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
            <rect width="20" height="20" fill="#ffffff" /> 
            <circle cx="10" cy="10" r="5" stroke="#0000bb" fill="#dd8d8d" /> 
        </pattern>
    </defs>
    <text y="100%"
        stroke="#ff0000"
        fill="url('#myPattern')"
        font-size="40pt">
        Hello <tspan style="font-style: italic">SVG</tspan> world!
    </text>
</svg>
SVG;

try{

    $image = new Imagick();
    $image->setBackgroundColor(new ImagickPixel('transparent'));
    $image->readImageBlob( $svg );
    $image->setImageFormat('png32');
    $image->setImageCompressionQuality(100);

    file_put_contents('text-fill-example.png', $image);
}
catch(ImagickException $e){
    error_log($e);
}

在上面的示例中,字母应包含点状图案。如果您在Inkscape中将上述svg代码作为文件打开,则该模式会正确显示。此外,如果您将svg代码嵌入到html中,它会在现代浏览器中正确显示模式。

如果我尝试从命令行转换,也会忽略该模式:

$ convert -verbose text-fill-example.svg text-fill-example.png 
text-fill-example.svg SVG 358x36 358x36+0+0 16-bit DirectClass 433B 0.020u 0:00.030
text-fill-example.svg=>text-fill-example.png SVG 358x36 358x36+0+0 16-bit PseudoClass 256c 8.19KB 0.010u 0:00.009

$ convert --version
Version: ImageMagick 6.7.7-10 2014-03-06 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2012 ImageMagick Studio LLC
Features: OpenMP    

有人对此有所了解吗?

1 个答案:

答案 0 :(得分:0)

原来我的SVG代码并不完全有效。我使用W3C validator得到了一些100%有效的标记,现在它可以工作了:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
    <defs>
        <pattern id="myPattern" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
            <rect width="20" height="20" fill="#ffffff" /> 
            <circle cx="10" cy="10" r="5" stroke="#0000bb" fill="#dd8d8d" /> 
        </pattern>
    </defs>
    <text y="100%"
        stroke="#ff0000"
        fill="url(#myPattern)"
        font-size="40pt">
        Hello <tspan style="font-style: italic">SVG</tspan> world!
    </text>
</svg>