首页 > 解决方案 > How to change dimensions of SVG and print it as PNG?

问题描述

I have an svg file, which contains a small vector. It looks like this:

Tiny Vector

I have the following code which converts SVG to PNG:

$imagick = new Imagick();
$imagick->setBackgroundColor(new ImagickPixel("transparent"));
$imagick->readImageBlob(file_get_contents($_GET['src']));
$imagick->setImageFormat('png32');

// Print
header("Content-Type: image/png");
echo $imagick;

$imagick->clear();
$imagick->destroy();

return;

Which is accessible using: http://localhost/imagick.php?src=Untitled-1.svg

And I want to resize the SVG and keep the quality, like Wikipedia does, for example:

http://localhost/imagick.php?src=Untitled-1.svg&dimensions=[250] Or http://localhost/imagick.php?src=Untitled-1.svg&dimensions=[250,250]

and then to print it with the new dimensions:

if (isset($_GET['dimensions'])) {
    $_GET['dimensions'] = json_decode($_GET['dimensions']);
    $imagick->resizeImage(
        (isset($_GET['dimensions'][0]) ? $_GET['dimensions'][0] : 0),
        (isset($_GET['dimensions'][1]) ? $_GET['dimensions'][1] : 0),
        Imagick::FILTER_UNDEFINED,
        0.5
    );
}

But when I do it, The quality is REALLY BAD:

Awful Quality

How can I preserve the original quality so it will be something like:

Way much better quality

?

Full Code:

$imagick = new Imagick();
$imagick->setBackgroundColor(new ImagickPixel("transparent"));
$imagick->readImageBlob(file_get_contents($_GET['src']));

if (isset($_GET['dimensions'])) {
    $_GET['dimensions'] = json_decode($_GET['dimensions']);
    $imagick->resizeImage(
        (isset($_GET['dimensions'][0]) ? $_GET['dimensions'][0] : 0),
        (isset($_GET['dimensions'][1]) ? $_GET['dimensions'][1] : 0),
        Imagick::FILTER_UNDEFINED,
        0.5
    );
}

$imagick->setImageFormat('png32');

// Print
header("Content-Type: image/png");
echo $imagick;

$imagick->clear();
$imagick->destroy();

return;

标签: phpimagemagickimagick

解决方案


推荐阅读