我正在将SVG文件的字符串表示发送到服务器,并使用Imagick以以下方式将其转换为JPEG:
$image = stripslashes($_POST['json']);
$filename = $_POST['filename'];
$unique = time();
$im = new Imagick();
$im->readImageBlob($image);
$im->setImageFormat("jpeg");
$im->writeImage('../photos/' . $type . '/humourised_' . $unique . $filename);
$im->clear();
$im->destroy();
然而我希望在栅格化之前调整SVG的大小,以便生成的图像比SVG文件中指定的尺寸更大。
我将我的代码修改为以下内容:
$image = stripslashes($_POST['json']);
$filename = $_POST['filename'];
$unique = time();
$im = new Imagick();
$im->readImageBlob($image);
$res = $im->getImageResolution();
$x_ratio = $res['x'] / $im->getImageWidth();
$y_ratio = $res['y'] / $im->getImageHeight();
$im->removeImage();
$im->setResolution($width_in_pixels * $x_ratio, $height_in_pixels * $y_ratio);
$im->readImageBlob($image);
$im->setImageFormat("jpeg");
$im->writeImage('../photos/' . $type . '/humourised_' . $unique . $filename);
$im->clear();
$im->destroy();
这段代码应该能够确定分辨率并相应地调整SVG大小。如果SVG画布和其元素具有基于百分比的宽度,则可以完美运行,但是对于以'px'定义的元素似乎无法正常工作。而这恰恰是必需的。
将发送到服务器的典型SVG字符串如下所示:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd">
<svg id="tempsvg" style="overflow: hidden; position: relative;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="333" version="1.1" height="444">
<image transform="matrix(1,0,0,1,0,0)" preserveAspectRatio="none" x="0" y="0" width="333" height="444" xlink:href="http://www.songbanc.com/assets/embed/photos/full/133578615720079914224f9e7aad9ac871.jpg"></image>
<image transform="matrix(1,0,0,1,0,0)" preserveAspectRatio="none" x="85.5" y="114" width="50" height="38" xlink:href="http://www.songbanc.com/assets/embed/humourise/elements/thumb/thumb_lips4.png"></image>
<path transform="matrix(1,0,0,1,0,0)" fill="none" stroke="#000" d="M110.5,133L140.5,133" stroke-dasharray="- " opacity="0.5"></path>
<circle transform="matrix(1,0,0,1,0,0)" cx="140.5" cy="133" r="5" fill="#000" stroke="#000"></circle>
<path transform="matrix(1,0,0,1,0,0)" fill="none" stroke="#000" d="M110.5,133L110.5,155.8" stroke-dasharray="- " opacity="0.5"></path>
<circle transform="matrix(1,0,0,1,0,0)" cx="110.5" cy="155.8" r="5" fill="#000" stroke="#000"></circle>
<circle transform="matrix(1,0,0,1,0,0)" cx="110.5" cy="133" r="5" fill="#000" stroke="#000"></circle>
</svg>
正如您所看到的,构成此SVG的元素具有像素定义的宽度和高度(对于此应用程序不幸的是使用百分比不是一个选项)。
有什么解决方法吗?或者有没有其他将SVG转换为PNG并在给定大小下呈现而不损失质量的方法。
谢谢。
编辑:虽然我从未真正找到完美的解决方案。相反,我最终将SVG数据作为JSON发送,通过服务器端循环遍历并将像素缩放到预期高度。
然后,在经过多次尝试之后,我意识到imagemagick存在问题,无法处理标准SVG变换/旋转命令,从而使任何操作的元素失调。我最终切换到使用“inkscape”将生成的SVG渲染为光栅图像。一切都很好。我仍在深入研究一个潜在的公式解决方案,以抵消imagemagick所做出的差异。如果我有任何成功,我会再次更新这个问题。
:)
。 - halfer