NiftyPixel NiftyPixel - 23 days ago 13
PHP Question

Change php base64_decode resolution on output?

I'm using the following code to show an image

$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);


I was wondering if it was possible to scale or change the dimensions of the image prior to rendering on the page. Since Google Insight images are only 320x240 natively, I need to scale it up to let's say 600x600 for example.

Thank you for any help/input.

Answer

Base64 data is a text representation of binary data. As @MagnusEriksson said you'll have to convert it if you want to increase its size.

Complicated Solution

You can use imagecreatefromstring to create an image within PHP, scale it up by possibly using imagescale and finally output your newly scaled image.

$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.';
}

It's worth mentioning that if you have a PHP version of PHP 5.5.18 or earlier, or PHP 5.6.2 or earlier, you need to provide both width and height params to imagescale as the aspect ratio calculation was incorrect.

Also your image, as you are scaling up (making it bigger), will be of poor quality compared to the original... there won't be enough data in the original image to create a nice high res version of it.

Easier Solution

As you don't actually benefit from increasing the scale, if you have control over where it is used, you could simply add CSS styles to the image to increase the size.

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

This would achieve the same effect, without any PHP code to alter the image.