Google PageSpeed Insights API Screenshot to file
Asked Answered
M

3

5

I have been trying to retrieve the screenshot from the API but when I decode the image and save it I get a broken image. Below is the code I am using. I created a tinyurl to a sample file containing a google response if you wish to test it.

$name = 'test';
$result = file_get_contents('http://tinyurl.com/q4smyod'); 
$result = json_decode($result, true);
$decoded=base64_decode($result['screenshot']['data']);
file_put_contents('img/'.$name.'.jpg',$decoded);
Monika answered 2/4, 2015 at 5:21 Comment(0)
M
14

As mentioned in my comment the issue is being caused by an error on googles encryption when working with the php api. If you are having this issue simply use the following replace functions to fix the encoding.

$data    = str_replace('_','/',$result['screenshot']['data']);
$data    = str_replace('-','+',$data);
$decoded = base64_decode($data);
Monika answered 2/4, 2015 at 7:20 Comment(1)
Nice! it works perfectly. Thanks. Is there any possibility to run runpagespeed to get screenshot.width and screenshot.height other than the default of 320px,240px?Intra
R
0

This should help get you closer to your goal. You didn't have a name defined and your json_decoding was a bit strange:

<?php
     error_reporting(-1);
     ini_set('display_errors', 'On');
     $result = file_get_contents('http://tinyurl.com/q4smyod'); 
     $name = 'test2';
     $result = json_decode($result, true);

     $decoded = base64_encode($result['screenshot']['data']);
     file_put_contents($name.'.jpg',$decoded);

?>
Rosemari answered 2/4, 2015 at 5:55 Comment(9)
This did nothing more than change the method in which i was decoding. I know that the name was not declared in the code but as I mentioned the file is created but not correctly. I hope this does not effect my chances of getting a real answer.Monika
You got a real answer, how can you check an image that has no file name to begin with? Now that you have data being written to a file with a file name, and it's decoded the proper way, maybe you can figure out how to write to the file properly.Rosemari
And if you didn't want help, then maybe you shouldn't have asked.Rosemari
1 the method of decoding that was changed was the way the json was decoded not the image. 2 the image had a name I just missed copying it when I gave you guys a sample. 3 when you submit a code to someone you should make sure it works. Thus the reason I gave a sample export from google.Monika
The code given above does the exact same thing as the code I suppliedMonika
When you come to SO, you come to learn, and people put you on the right path, not supply you with the direct answers all the time.Rosemari
The comment did not point me in the right direction. It simply repeated the code. With error reporting turned on which does nothing if you understand the way these functions work as coded.Monika
Understanding why you decoded the results, and then re-encoded then, and then re-decoded them again just by setting the true flag, which is what you could have done to begin with - is beyond me and my decade of experience of coding.Rosemari
It was because I was quickly copying code from my class file and I combine two systems into one and that was needed to pull content properly. Dont quote your experience if you are going to post code that does not work.Monika
E
-1

Currently I`m using Google Page Speed API to capture image via Web URL and save it to location I specify. This works without any issues. Please have a look. Comments are made to understand easily.

import urllib2
import json
import base64
import sys
import requests
import os
import errno

#   The website's URL as an Input
site = #specify the URL here
imagePath = #specify your path to save the image

#   The Google API.  Remove "&strategy=mobile" for a desktop screenshot
api = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?screenshot=true&strategy=mobile&url=" + urllib2.quote(site)

#   Get the results from Google
try:
    site_data = json.load(urllib2.urlopen(api))
except urllib2.URLError:
    print "Unable to retreive data"
    sys.exit()

try:
    screenshot_encoded =  site_data['screenshot']['data']
except ValueError:
    print "Invalid JSON encountered."
    sys.exit()

#   Google has a weird way of encoding the Base64 data
screenshot_encoded = screenshot_encoded.replace("_", "/")
screenshot_encoded = screenshot_encoded.replace("-", "+")

#   Decode the Base64 data
screenshot_decoded = base64.b64decode(screenshot_encoded)

if not os.path.exists(os.path.dirname(impagepath)):
    try:
        os.makedirs(os.path.dirname(impagepath))
        except  OSError as exc:
            if exc.errno  != errno.EEXIST:
                raise

#   Save the file
with open(imagePath, 'w') as file_:
    file_.write(screenshot_decoded)
Emelineemelita answered 4/11, 2019 at 3:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.