更改 php base64_decode 输出分辨率?

Change php base64_decode resolution on output?

我正在使用以下代码显示图像

$imgstring = file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=".$_GET['url']."&screenshot=true");

$imgstring = json_decode($imgstring);
$imgstring = $imgstring->screenshot->data;

$imgstring = str_replace("_", "/", $imgstring);
$imgstring = str_replace("-", "+", $imgstring);

header('Content-Type: image/png');
echo base64_decode($imgstring);

我想知道是否可以在页面上呈现之前缩放或更改图像的尺寸。由于 Google Insight 图像本身只有 320x240,我需要将其放大到例如 600x600。

感谢任何help/input。

Base64 数据是二进制数据的文本表示。正如@MagnusEriksson 所说,如果你想增加它的大小,你必须转换它。

复杂的解决方案

您可以使用imagecreatefromstring to create an image within PHP, scale it up by possibly using imagescale并最终输出您新缩放的图像。

$imgstring = file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=".$_GET['url']."&screenshot=true");

$imgstring = json_decode($imgstring);
$imgstring = $imgstring->screenshot->data;

$imgstring = str_replace("_", "/", $imgstring);
$imgstring = str_replace("-", "+", $imgstring);

$im = imagecreatefromstring(base64_decode($imgstring));
$im = imagescale($im, 600);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
} else {
    header('Content-Type: text/plain');
    echo 'An error occurred.';
}

值得一提的是,如果您有 PHP 版本 PHP 5.5.18 或更早版本,或者 PHP 5.6.2 或更早版本,您需要同时提供宽度和由于宽高比计算不正确,高度参数设置为 imagescale

此外,当您放大(使其变大)时,您的图像与原始图像相比质量会很差...原始图像中的数据不足,无法创建漂亮的高分辨率版本

更简单的解决方案

由于您实际上并没有从增加比例中获益,如果您可以控制它的使用位置,您可以简单地向图像添加 CSS 样式以增加尺寸。

<img src="myphp.php?url=someurl" style="width:600px;height:auto;" />

这将达到相同的效果,无需任何 PHP 代码来改变图像。