如何在php中使用imagick裁剪svg图像


how to crop svg image with imagick in php?

我有SVG图像,右侧和底部有很多空白。如何使用PHP和imagick裁剪图像(给定固定大小,所有图像都将具有相同大小),并将它们保存回相同的文件?

您根本不需要imagick。由于SVG是一种XML格式,您可以将文档加载到DOMDocument对象中,并更改SVG标记上的宽度和高度属性。

这里有一个例子(svg文件是从jenkov.com借来的):

<?php
$svg = <<< EOF
<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect x="50" y="50" height="110" width="110"
          style="stroke:#ff0000; fill: #ccccff"
          transform="translate(30) rotate(45 50 50)"
            >
    </rect>
    <text x="70" y="100"
          transform="translate(30) rotate(45 50 50)"
    >Hello World</text>
</svg>
EOF;
$myWidth = 100;
$myHeight = 150;
$dom = new DOMDocument();
$dom->loadXML($svg);
$svg = $dom->getElementsByTagName('svg');
$svg->item(0)->setAttribute('width', $myWidth);
$svg->item(0)->setAttribute('height', $myHeight);
print $dom->saveXML($svg->item(0))."'n";

听起来你想在svg文件中添加一个(紧密贴合的)viewBox,然后用imagemagik光栅化它们。

做第一步的一些选项:

  • SVG清理器
  • SVG Scour