将内联 svg 与 imagemagick 一起使用
using inline svg with imagemagick
我正在尝试确定从内联 SVG 图像转换为 png 图像的最佳方式(svg 是动态生成的,并根据用户输入进行更改)。
现在我有:
<?php
$svgtest = '
<svg width="100" height="100">
<text x="5" y="12">hi</text>
</svg>
';
exec("convert \"$svgtest\" \"test.png\" ");
?>
但这不起作用。
使用 ImageMagick 扩展和以下代码:
$im = new imagick();
$im->setBackgroundColor(new ImagickPixel('white'));
$svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg width="100" height="100"><text x="5" y="12">hi</text></svg>';
$im->readImageBlob($svg);
$im->setImageFormat("png");
$im->writeImage("out.png");
注意 SVG 字符串有 xml 声明。
要使用命令行,您始终可以读取 STDIN 或将字符串放入文件然后进行处理。但是,对于某些恶意用户输入,这更容易受到攻击。
echo "<?xml version='1.0' encoding='UTF-8' standalone='no'?><svg width='100' height='100'><text x='5' y='12'>hi</text></svg>" | convert - out2.png
要做到这一点,只需将上面的行传递到 exec()
我正在尝试确定从内联 SVG 图像转换为 png 图像的最佳方式(svg 是动态生成的,并根据用户输入进行更改)。 现在我有:
<?php
$svgtest = '
<svg width="100" height="100">
<text x="5" y="12">hi</text>
</svg>
';
exec("convert \"$svgtest\" \"test.png\" ");
?>
但这不起作用。
使用 ImageMagick 扩展和以下代码:
$im = new imagick();
$im->setBackgroundColor(new ImagickPixel('white'));
$svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg width="100" height="100"><text x="5" y="12">hi</text></svg>';
$im->readImageBlob($svg);
$im->setImageFormat("png");
$im->writeImage("out.png");
注意 SVG 字符串有 xml 声明。
要使用命令行,您始终可以读取 STDIN 或将字符串放入文件然后进行处理。但是,对于某些恶意用户输入,这更容易受到攻击。
echo "<?xml version='1.0' encoding='UTF-8' standalone='no'?><svg width='100' height='100'><text x='5' y='12'>hi</text></svg>" | convert - out2.png
要做到这一点,只需将上面的行传递到 exec()