screenshot using googlepagespeed api

Viewed 4953

Below is my code to capture the screenshot of of webpage. But i get the output of the same as how in the image below. Kindly suggest on what is the mistake i am committing. Also kindly suggest the method to save this screenshot to the server?

enter image description here

<?php
 $url='https://www.google.com';
 $stratedy = 'mobile' ;
 $apiReqUrl = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed';
 $apiKey = 'my_api_key' ;
 $curl = curl_init();
 curl_setopt($curl, CURL_OPTURL, $apiReqUrl.'?url='.$reqUrl.' 
 &key='.$apiKey.'&screenshot=true&strategy='.$stratedy);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
 $result=curl_exec($curl);
 $data = json_decode($result, true);
 $img = str_replace(array('_','-'), array('/','+'), $data['screenshot'] 
 ['data']);
 echo '<img src="data:image/jpeg;base64,'.$img.'">';
 ?>
2 Answers

If you can, try using the HTML version from Generating Screenshots of URLs using Google's secret magic API. All you need to do is to call the API and it's free (I guess).

For example in PHP:

<?php  

$url = "https://praveen.science/";

// Hit the Google PageSpeed Insights API.
// Catch: Your server needs to allow file_get_contents() to make this run. Or you need to use cURL.
$response = file_get_contents('https://www.googleapis.com/pagespeedonline/v2/runPagespeed?screenshot=true&url='.urlencode($url));

// Convert the JSON response into an array.
$googlePagespeedObject = json_decode($response, true);

// Grab the Screenshot data.
$screenshot = $googlePagespeedObject['screenshot']['data'];

// Fix url encoded base64
$screenshot = str_replace(array('_','-'), array('/','+'), $screenshot);

// Build the Data URI scheme and spit out an <img /> Tag.
echo "<img src=\"data:image/jpeg;base64,{$screenshot}\" alt=\"Screenshot\" />";

// Or.. base64 decode and store
file_put_contents('...', base64_decode($screenshot));

Or in JavaScript:

$(function() {
  // Get the URL.
  var url = "https://praveen.science/";
  // Prepare the URL.
  url = encodeURIComponent(url);
  // Hit the Google Page Speed API.
  $.get("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?screenshot=true&strategy=mobile&url=" + url, function(data) {
    // Get the screenshot data.
    var screenshot = data.screenshot;
    // Convert the Google's Data to Data URI scheme.
    var imageData = screenshot.data.replace(/_/g, "/").replace(/-/g, "+");
    // Build the Data URI.
    var dataURI = "data:" + screenshot.mime_type + ";base64," + imageData;
    // Set the image's source.
    $("img").attr("src", dataURI);
  });
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<h1>Hard Coded Screenshot of my Website:</h1>
<img src="//placehold.it/300x50?text=Loading+Screenshot..." alt="Screenshot" />

Related