Imagick SVG无法加载图像



我遇到了通过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

我是否需要安装任何其他扩展才能获得正确的结果?或者我的代码有任何问题?

我找到了解决方法。我在图像路径中使用 base64 图像内容。

$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);
}

如果可能,可以使用本地图像或网络网址。

如果您希望 Imagick 在转换时考虑您的图像,则不应使用指向图像的链接。请改用与这些图像对应的 base64 编码数据。这将起作用。

我遇到了这个问题并最终来到了这里,在评论中没有看到解决方案(必须单击"显示更多评论"),直到我自己修复了它,所以认为可能值得将其作为答案发布(以及投票):

正如@Phuc-Pham所发现的那样,问题在于Imagick想要整个服务器路径,而不是href属性中相对于CWD或HTTP文档根目录的路径。

因此,在解决方案中使用他的代码应该是这样的:

$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="/path/to/htdocs/wp-content/uploads/2012/10/capapix_Harley_Davidson_FLSTCI_-_Heritage_Classic.jpg"></image>
</svg>';

希望有用。

最新更新