Retrieve Images from the (Depreciated) Google Images API

The early version of the Google Images API was officially depreciated on the 26th May, 2011. Despite that, it will continue to work with some restrictions until such time as Google officially pulls the plug. With additional limitations – and more functionality – the image search is survived by the Google Custom Search API. With the new Google Custom Search API, it permits you to develop websites and programs to retrieve and display search results from Google Custom Search programmatically.

Details on how to use the API (both depreciated and Google Search) are available here and here. The scope of this post is limited to very basic usage… simply because they’re examples I’ve used in the past.

Function to Retrieve The Last 32 Images from the Depreciated API

This is a very basic function I’ve used in the past. Before you use it, you should be aware of your legal obligations. It will retrieve 32 image URL’s. While the data returned is quite significant, it’s only the image URL that I was interested in (when I wrote this).

<?php
$start = array(0, 4, 8, 12, 16, 20, 24, 28);
foreach ($start as &$p) {
  // Use your IP and your own query term (q)
  $jsrc = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=aircraft&userip=12.345.67.890&start=$p";
      $json = file_get_contents($jsrc); 
      $jset = json_decode($json, true);
    for($i=0;$i<4;$i=$i+1) {
    $image = $jset['responseData']['results'][$i]['url'];
    echo "$image<br>";
    $ImagesArray[] = $image;
   }
}

// Print the Image array

echo "<pre>";
print_r($ImagesArray);
echo "</pre>";
?>

Refining search by passing parameters in the query string

You may refine the nature of images returned by passing additional criteria in the search URL. They are listed, in part, as follows:

as_filetype=jpg restricts results to JPG images
as_filetype=png restricts results to PNG images
as_filetype=gif restricts results to GIF images
as_filetype=bmp restricts results to BMP images

Searching by licence type:

as_rights=cc_publicdomain restricts search results to images with the publicdomain label.
as_rights=cc_attribute restricts search results to images with the attribute label.
as_rights=cc_sharealike restricts search results to images with the sharealike label.
as_rights=cc_noncommercial restricts search results to images with the noncomercial label.
as_rights=cc_nonderived restricts search results to images with the nonderived label.

Searching by specific site:

as_sitesearch=photobucket.com

Searching by color:

imgcolor=black
imgcolor=blue
imgcolor=brown
imgcolor=gray
imgcolor=green
imgcolor=orange
imgcolor=pink
imgcolor=purple
imgcolor=red
imgcolor=teal
imgcolor=white
imgcolor=yellow

Searching by Image Size

imgsz=icon restricts results to small images
imgsz=small|medium|large|xlarge restricts results to medium-sized images
imgsz=xxlarge restricts results to large images
imgsz=huge restricts resykts to extra-large images

Searching by Image Type

imgtype=face restricts results to images of faces.
imgtype=photo restricts results to photographic images.
imgtype=clipart restricts results to clipart images.
imgtype=lineart restricts results to line drawing images.

A full list of all available parameters are available here. The parameter of userip=12.345.67.890 is important. It should be set to the IP address of the user making the request; Image automation is not permitted.

Retrieve a Single Image from the Google Search Page

If you’re just after a single result, you may want to consider mining the image results from the default search page. The following function will do just that — pull up the first page and retrieve the first image URL. You can use the custom (or advanced) search to narrow or refine your result.

The legality of this technique is somewhat questionable and a copyright will likely apply to the image returned (even when a public domain search is conducted).

<?php
$link = "http://images.google.com/images?q=flying&tbm=isch";
$code = file_get_contents($link,'r');

ereg ("imgurl=http://www.[A-Za-z0-9-]*.[A-Za-z]*[^.]*.[A-Za-z]*", $code, $img);
ereg ("http://(.*)", $img[0], $img_pic);

$firstImage = $img_pic[0];
$firstImage = trim("$firstImage");
echo "$firstImage<br><br>";

// Display image
echo "<img src=\"$firstImage\">";
?>

More from the Google Search API another time! Download the above code here.

First Name:
Your Email Address:
 




Download: Google Image Search API
Description: Google Image Search API
Author:Marty
Category: PHP code
Date: July 18, 2012



If you liked this article, you may also like:

  1. Google’s Weather & other Secret API’s
  2. Replace YouTube Links in Text with Embed Code (and Retrieve Video Details via the JSON API)
  3. Determine the Status of a Remote Webpage and Retrieve the HTTP Status Code
  4. Generate QR Codes on Your Website or WordPress Post with Google Chart Tools
  5. Retrieve Data from a Remote Webpage
About Marty

is a passionate web developer from Sydney, Australia. He owns about 600 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. Follow Marty on Twitter or Google+.

Comments

  1. Amed says:

    I’m interested in using the “Retrieve a Single Image from the Google Search Page” in my WordPress sidebar.

    What I want to do is to display the image corresponding to the category name (%category%) of the post.

    What part of the code mentioned above should I change to make it dinamic?

    Should it be like this:
    <?php
    $link = "http://images.google.com/images?q=&tbm=isch“;
    $code = file_get_contents($link,’r');
    ereg (“imgurl=http://www.[A-Za-z0-9-]*.[A-Za-z]*[^.]*.[A-Za-z]*”, $code, $img);
    ereg (“http://(.*)”, $img[0], $img_pic);
    $firstImage = $img_pic[0];
    $firstImage = trim(“$firstImage”);
    echo “$firstImage”;

    // Display image
    echo “”;
    ?>

  2. Marty says:

    HI Ahmed. I’d suggest you do it with shortcode to save you messing around with your theme’s files. Where do you want the image?

    Keep in mind that this is questionably legal. You really wouldn’t want to indiscriminately render any image on your page without considering the legal/copyright implications.

    Give me 10 minutes and I’ll post some test code.

    • Marty says:

      Hi again,

      I’ve written this without really testing it beyond one page so I’m not sure it’ll always work. URL’s will cache for 3 hours. It’ll scrape the Google Page (perhaps use cURL) and it won’t use the API.

      [googlepic] will render an image associated with the current category…. while [googlepic term="cat"] will render an image based on the defined term.

      You’ll probably want to locally cache the image and you’ll amost certainly have to resize it using GD or similar.

      Be careful using this. Copyright restrictions apply.

      function GetGooglePic($atts) {
      extract(shortcode_atts(array(
          'term' => '',
          'cache' => '10800' // 60*60*3 (3 hours)
        ), $atts));
      
       $GoogleImageCache = 'gimglink_' . $term;
       $cachedposts = get_transient($GoogleImageCache);
       if ($cachedposts !== false) {
       $firstImage == $cachedposts;
      
       } else {
      
       if ($term) {
        $link = "http://images.google.com/images?q=$term&tbm=isch";
        } else {
        // Have to get category name (for query)
        $terms = get_the_terms( $post->ID , 'category');
        if($terms) {
            foreach( $terms as $term ) {
              $cat_obj = get_term($term->term_id, 'category');
              $cat_slug = $cat_obj->slug;
            }
           }
          // return $cat_slug;
          $link = "http://images.google.com/images?q=$cat_slug&tbm=isch";
          }
        // Now get the pic and cache
        $code = file_get_contents($link,'r');
      
        ereg ("imgurl=http://www.[A-Za-z0-9-]*.[A-Za-z]*[^.]*.[A-Za-z]*", $code, $img);
        ereg ("http://(.*)", $img[0], $img_pic);
      
        $firstImage = $img_pic[0];
        $firstImage = trim("$firstImage");
       }
       // Apply function to do something with returned link
       return $firstImage;
      }
      add_shortcode('googlepic','GetGooglePic');
      • Marty says:

        I should have mentioned that, as always, the code will have to be pasted in your theme’s functions.php file. Let me know if you have problems.

Speak Your Mind

*