在 PHP 中将 SVG 文件渲染为 PNG 或 JPEG

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10289686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:49:54  来源:igfitidea点击:

Rendering an SVG file to a PNG or JPEG in PHP

phpsvggdlib

提问by DanRedux

I've googled as much as I can, but I've only found a PHP class that calls upon Inkscape to render the SVG, so I ask here:

我已经尽可能多地搜索了谷歌,但我只找到了一个调用 Inkscape 来渲染 SVG 的 PHP 类,所以我在这里问:

I have a valid SVG file generated in some way (or uploaded by a client). I need to render this into a JPG or PNG using just PHP and/or GDLib, as SVG is not supported by all browsers.

我有一个以某种方式生成的有效 SVG 文件(或由客户端上传)。我需要仅使用 PHP 和/或 GDLib 将其呈现为 JPG 或 PNG,因为并非所有浏览器都支持 SVG。

I do not have the option of installing anything, so a class that converts SVG to PNG using GDLib would be the most ideal.

我没有安装任何东西的选项,因此使用 GDLib 将 SVG 转换为 PNG 的类将是最理想的。

回答by David Z.

Check if ImageMagick is installed (you can find out using phpinfo). If it is, you can use the following code to cover to a PNG.

检查是否安装了 ImageMagick(您可以使用 找到phpinfo)。如果是,您可以使用以下代码覆盖到 PNG。

$image = new Imagick();
$image->readImageBlob(file_get_contents('image.svg'));
$image->setImageFormat("png24");
$image->resizeImage(1024, 768, imagick::FILTER_LANCZOS, 1); 
$image->writeImage('image.png');

There are many threads that discuss this. One that is particularly useful is this thread: Convert SVG image to PNG with PHP

有很多线程讨论这个。特别有用的是这个线程: Convert SVG image to PNG with PHP