简体   繁体   English

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

[英]how to crop svg image with imagick in php?

I have SVG images, with lots of white space on the right side and at the bottom. 我有SVG图片,右侧和底部都有很多空白。 How do I crop the image (given a fixed size, all images are going to be of same size) using PHP and imagick, and save them back to the same files? 如何使用PHP和imagick裁剪图像(给定大小,所有图像大小均相同),然后将其保存回相同的文件?

You shouldn't need imagick for this at all. 您完全不需要想象力。 Since SVG is an XML-format you can load the document into a DOMDocument object and change the width and height attributes on the svg tag. 由于SVG是一种XML格式,因此您可以将文档加载到DOMDocument对象中,并更改svg标签上的width和height属性。

Here's an example (the svg file is borrowed from jenkov.com ) : 这是一个示例(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";

Sounds like you want to add a (tightly fitting) viewBox to your svg files, and then rasterize them with imagemagick. 听起来好像您想向您的svg文件添加一个(紧密适合的)viewBox,然后使用imagemagick对其进行栅格化。

Some options for doing the first step: 第一步的一些选择:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM