How to read an SVG with a given size using PHP Imagick?

落爺英雄遲暮 提交于 2019-12-10 09:41:31

问题


I have the following code:

$image = new Imagick();
$image->setBackgroundColor(new ImagickPixel('green'));
$image->setSize(20,20);
$image->readImageBlob(file_get_contents('./some/path/image.svg'));

It loads the SVG just fine but the setSize just gets completely ignored. It renders at 550x100, as per it's definition:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
    width="550px" height="100px" viewBox="0 0 550 100" 
    enable-background="new 0 0 550 100" xml:space="preserve">

Has anyone got experience in getting SVG files to play nice with setSize?


回答1:


The setSize() function is only for raw image formats, not SVG. You need to use scaleImage() instead...

$image = new Imagick();
$image->setBackgroundColor(new ImagickPixel('green'));
$image->readImage('./some/path/image.svg');
$image->scaleImage(20,20);

By the way, that will work fine if you're downscaling your SVG image to a smaller size (as you are in this case), for for anyone who is upscaling it instead, you need to do one other thing. If you just change the size as above, it will appear jagged and pixelated. In that case you need to use setResolution() to increase the resolution like this:

$image = new Imagick();
$image->setResolution(2000,2000);
$image->setBackgroundColor(new ImagickPixel('green'));
$image->readImage('./some/path/image.svg');
$image->scaleImage(1000,1000);

The actual values for setResolution() should be computed as 72 * (final_size / original_size) (well, I think that's the correct formula anyway). But any value that's at least that value or higher will also work fine.




回答2:


Regarding up-scaling SVGs: With my current setup (ImageMagick 6.7.8-1 2012-10-03 Q16 with SVG rw+) an SVG saved at 90x30 pixels cannot be scaled up even with setResolution() and setImageResolution(). If I instead re-save the SVG at a higher size, like 9000x3000, I can safely size it up or down with the above instructions.



来源:https://stackoverflow.com/questions/9226232/how-to-read-an-svg-with-a-given-size-using-php-imagick

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!