Creating a website screenshot is never been easy. there''s a lot of libraries on Github to do such task but would require importing many libraries, configuration..etc..
fortunately Google has this API called PageSpeed API
wherein we can use it by just calling the PageSpeed url and btw, no API key required! how cool is that!
once called, this API will return a json data which contains the screenshot image of the target website (base64_encoded text)
To call the API, simply make a GET request to this url
Just replace the "url" with your target website, while the "strategy" parameter has 2 values (desktop|mobile)
default is "desktop"
once the API is called, output should be like this
that''s a bunch of base64_encoded data!
to display the actual image we are going to parse the json. on our example i will use PHP
here is the short code
$url = "http://google.com";
$data = json_decode(file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$url&screenshot=true&strategy=desktop"));
// encoded base64 image
$base64_str = $data->screenshot->data;
// replace the returned base64 string
$base64_str = str_replace(''_'',''/'',$base64_str);
$base64_str = str_replace(''-'',''+'',$base64_str);
// output as jpeg file
$decoded = base64_decode($base64_str);
On my code you will see that i replaced some of the strings of the returned base64 data and as been said on the API documentation:
Output (base on the code)
If you''ll change the value of "strategy" parameter to "mobile", the output will be like this
One of the limitations of this API is the fixed image size. It''s only 320x240 pixels. I hope they update their API in the future to let the developer set the screenshot size.
Okay, that''s it! :)