如何使用 Inkscape 将 SVG 字符串转换为 jpg


How to convert an SVG string into a jpg with Inkscape

在花了两天时间尝试使用ImageMagick从SVG字符串中栅格化jpeg之后,我终于放弃了。

虽然我设法让实际的转换工作正常,但似乎 Imagemagick 在渲染图像时无法正确转换转换/旋转功能,使输出与原始 SVG 不同。

经过进一步研究,这似乎是一个已知问题,"Inkscape"是在PHP中将SVG转换为jpeg/png的最佳方法。

问题是我的SVG数据通过JSON发送到我的PHP脚本。 如何将 blob 或字符串放入 Inkscape 命令行以进行转换?

非常感谢您的任何建议。

如果你有一个 SVG 字符串,并且通过 AJAX 将其从浏览器发送到服务器,则需要将其写入临时文件,以便可以从 Inkscape 命令行引用它。你不能使用Inkscape命令行渲染为JPEG,但你可以很容易地渲染成PNG,如果你真的需要不同的格式,当然你可以随后使用ImageMagick进行转换。

您需要类似以下内容:

/path/to/inkscape '
    --without-gui '
    --export-png=/path/to/output.png '
    /tmp/file/input.svg

如果您接受用户的全部/部分 SVG 输入,请记住,您需要牢记许多安全问题。如果需要,很高兴对此进行扩展。

您可以使用 stdin将 SVG 字符串传递给 inkscape,但代码的可移植性较差。

// Open Inkscape process
$process = proc_open(
    '/path/to/inkscape -z -f /dev/fd/0 -e /path/to/output' 
    array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')), 
    $pipes
);
// Write svg to stdin
fwrite($pipes[0], $svg);
// Close process
foreach ($pipes as $pipe) fclose($pipe);
proc_close($process);