我遇到了通过PHP Imagick库将SVG转换为图像的问题。 这是我的代码:
$svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg style="overflow: hidden; position: relative;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="754" version="1.1" height="565">
<defs></defs>
<image transform="matrix(1,0,0,1,0,0)" preserveAspectRatio="none" x="0" y="0" width="754" height="565" xlink:href="http://1439.demo.tekk3.com/wp-content/uploads/2012/10/capapix_Harley_Davidson_FLSTCI_-_Heritage_Classic.jpg"></image>
</svg>';
$im = new Imagick();
$im->readImageBlob($svg);
$im->setImageFormat("jpeg");
$im->writeimage($attached_file);
$im->clear();
$im->destroy();
结果是只有白色背景的图像。 SVG显示没有任何其他图像。
如果我将文本标记放入SVG字符串中,则只显示在白色背景中呈现的文本。图像仍然缺失。
我已经安装了php5-imagick,libxml2,librsvg2-bin
我是否需要安装任何其他扩展才能获得正确的结果? 或者我的代码有问题吗?
答案 0 :(得分:2)
我找到了解决方法。我使用base64图像内容instand的图像路径。
$svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="754" version="1.1" height="565">
<image x="0" y="0" width="754" height="565" xlink:href="'.imageToBase64('icons-weather_01.png').'"></image>
</svg>';
function imageToBase64($path) {
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
return 'data:image/' . $type . ';base64,' . base64_encode($data);
}
如果可能的话,使用本地图像或网址。
答案 1 :(得分:0)
如果您希望Imagick在转换时考虑您的图像,则不应使用图像链接。 而是使用与这些图像对应的base64编码数据。这将有效。
答案 2 :(得分:0)
我遇到了这个问题并最终在这里,没有看到评论中的解决方案(不得不点击“显示更多评论”),直到我自己修复它,所以认为可能值得将其发布为一个答案(以及upvoting):
正如@ Phuc-Pham所发现的,问题是Imagick想要整个服务器路径,而不是href属性中相对于CWD或HTTP文档根的路径。
因此,在解决方案上面使用他的代码应该是:
{{1}}
希望这很有用。