使用渐变将SVG转换为PNG时,白色背景错误

时间:2018-04-05 11:04:30

标签: php svg imagick

我想将SVG图像转换为保持透明度的PNG。在纯色形状的情况下工作正常,但是当用渐变填充形状时,输出图像会呈现意外的纯白色背景。

我想要一些使用Imagick库的解决方案,但也可以接受一些预处理svg代码的代码。

这是问题的最小例子:

<?php
$svg = <<<SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="100" height="100">
   <ellipse style="fill:red" cx="50" cy="50" rx="50" ry="50" />
</svg>
SVG;

$img = new \Imagick();
$img->readImageBlob($svg);
$img->setImageBackgroundColor('transparent');

//IMAGE WITH NICE TRANSPARENT BACKGROUND
$img->writeImage(__DIR__ . '/circle_plain.png');


$svg = <<<SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="100" height="100">
  <defs>
    <linearGradient
       id="linearGradient1">
      <stop
         style="stop-color:#ff0000;stop-opacity:1;"
         offset="0"/>
      <stop
         style="stop-color:#00ff00;stop-opacity:1;"
         offset="1"/>
    </linearGradient>
    <linearGradient
       xlink:href="#linearGradient1"
       id="linearGradient2"
       x1="0"
       y1="50"
       x2="100"
       y2="50"
       gradientUnits="userSpaceOnUse" />
  </defs>
  <ellipse style="fill:url(#linearGradient2)" cx="50" cy="50" rx="50" ry="50" />
</svg>
SVG;

$img = new \Imagick();
$img->readImageBlob($svg);
$img->setImageBackgroundColor('transparent');

//IMAGE WITH WRONG WHITE BACKGROUND!!
$img->writeImage(__DIR__ . '/circle_gradient.png');

0 个答案:

没有答案
相关问题