24

Since Google image search API is deprecated, one should use Google custom search API for this.

I've made a small example using it. My problem is I want to return google image search results only. Whereby this shows web results, and the user may switch to the image result. How can I show only the image results by default?

<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
  google.load('search', '1', {language : 'hu'});
  google.setOnLoadCallback(function() {
    var customSearchOptions = {
        enableImageSearch: true,
        imageSearchOptions: {
              layout: google.search.ImageSearch.LAYOUT_CLASSIC
        }
    };

    var options = new google.search.DrawOptions();
    options.setAutoComplete(true);

    var customSearchControl = new google.search.CustomSearchControl('XXX', customSearchOptions);

    customSearchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
    customSearchControl.setAutoCompletionId('XXX');

    customSearchControl.draw('cse', options);
  }, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />

The API documentation is quite poor, it only describes how to add additional results.

Tasos K.
  • 7,669
  • 7
  • 38
  • 57
sibidiba
  • 5,974
  • 7
  • 35
  • 50

7 Answers7

35

Google images search is now supported in the Custom Search Engine API. See the API parameters section of this page. I'm using the API with python and for my application I just specify the parameter in the API call.

searchType = "image"

See this post on the cse blog.

EDIT: As Marc points out in his comment below, you need to click "Enable image search" in your CSE console.

kelorek
  • 5,717
  • 6
  • 26
  • 32
  • 11
    To do this you need to click "Enable image search" in your CSE console! – Marc Jan 01 '13 at 12:45
  • Marc, that was exactly what I was missing! I created a custom search so that I have a cx param, but entered *.google.com as the domain. Enabling that image search now searches the images on google. Thanks a gazillion! – Jos Faber Apr 25 '13 at 14:17
  • 3
    I think [this](https://developers.google.com/custom-search/json-api/v1/reference/cse/list) is the documentation of parameters you can send, including `searchType`. – Carl G Nov 11 '16 at 10:27
  • Wow great, can you also kindly tell how to download this image or use it ? – Chandraprakash Jul 16 '20 at 01:02
5

Per the Google Custom Search Element Control API - documentation web site, this is possible.

https://developers.google.com/custom-search/docs/element

This is the fragment used for searching by image by default:

'defaultToImageSearch'

So I believe the full syntax for using this would be:

<script>
.
// Google custom search code, ids go here...
.
</script>
<gcse:search></gcse:search>
**<gcse:searchresults enableImageSearch="true" defaultToImageSearch="true">**
Paul Kane
  • 91
  • 1
  • 2
4

For those going through the WebExtensions tutorial, here's the updated code I used in popup.js to make it work with the new CSE functionality:

/**
 * @param {string} searchTerm - Search term for Google Image search.
 * @param {function(string,number,number)} callback - Called when an image has
 *   been found. The callback gets the URL, width and height of the image.
 * @param {function(string)} errorCallback - Called when the image is not found.
 *   The callback gets a string that describes the failure reason.
 */
function getImageUrl(searchTerm, callback, errorCallback) {
  // Google image search - 100 searches per day.
  // https://developers.google.com/image-search/
  // var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
  //   '?v=1.0&q=' + encodeURIComponent(searchTerm);
  var searchUrl = 'https://www.googleapis.com/customsearch/v1' +
    '?key=' + key + '&cx=' + cx + '&searchType=image&q=' + encodeURIComponent(searchTerm);

  var x = new XMLHttpRequest();
  x.open('GET', searchUrl);
  // The Google image search API responds with JSON, so let Chrome parse it.
  x.responseType = 'json';
  x.onload = function() {
    // Parse and process the response from Google Image Search.
    var response = x.response;
    if (!response || !response.items || response.items.length === 0) {
      errorCallback('No response from Google Image search!');
      return;
    }
    var firstResult = response.items[0];
    // Take the thumbnail instead of the full image to get an approximately
    // consistent image size.
    var imageUrl = firstResult.image.thumbnailLink;
    var width = parseInt(firstResult.image.thumbnailWidth);
    var height = parseInt(firstResult.image.thumbnailHeight);
    console.assert(
        typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
        'Unexpected respose from the Google Image Search API!');
    callback(imageUrl, width, height);
  };
  x.onerror = function() {
    errorCallback('Network error.');
  };
  x.send();
}

Mainly it's changing the search URL (which should have searchType=image as mentioned) and the response structural references in getImageUrl, and setting up the CSE engine. Make sure your CSE has Image search turned on, and under Sites to search make sure to select Search the entire web but emphasize included sites from the options list.

user10000000
  • 161
  • 1
  • 7
  • I'm trying to follow this code...is search term an image and you're looking for websites displaying that image or is search term a string and you're looking for images? I am trying to do the former...thank you! – GarySabo May 11 '17 at 14:40
  • @GarySabo in this case searchTerm is a string used to find the image files, so for example "youtube" would probably find a youtube logo image. for what you want to accomplish it sounds like you need tell the search engine exactly how websites are accessing the image, maybe using the image URL as the search term instead but there might be a better way of doing it – user10000000 May 12 '17 at 18:33
3

I'm not 100% certain on this, but I don't think the API supports what you're trying to do. This is not at all surprising, as Google's search API's are infamous for being lacking in even basic functionality (such as the standard search API's limit of 20 results, etc). I think the fact that I'm the first person to answer this in the 3 days it's been active is another indication that this is probably just not supported (or, if it is, Google never bothered to tell anyone).

I know you're not going to like this, but I think your best option is to scrape the images out of the returned result set yourself. That's typically what people have to resort to when dealing with Google results data. Fortunately, their frontend code is remarkably consistent, so a few well-tuned regex matches and/or splits should do the trick for ya.

And yes, it's total BS that Google has provided such lousy support for this API. =)

Kris Craig
  • 918
  • 1
  • 6
  • 15
  • 1
    Oh and if you do wind up adding a parsing layer to grab the images, I would strongly encourage you to OSS it on SF or Github and post a link here so other people Googling with this problem won't have to re-invent the wheel. – Kris Craig Dec 12 '11 at 22:36
  • 1
    Why I'm curious about it is, that previously they do had a separate API for image search only. – sibidiba Dec 13 '11 at 09:35
2

Try adding this line:

customSearchOptions['disableWebSearch'] = true;
2

Try this one

customSearchOptions['searchType'] = "image"
customSearchOptions['enableImageSearch'] = true
customSearchOptions['disableWebSearch'] = true;
msroot
  • 781
  • 10
  • 13
2

I tried to get a more authoritative answer in the official Google AJAX APIs group, and it seems the answer is NO(!). Google custom search API currently does not support image search only. You can use the deprecated Google image search API instead.

check this

swiftBoy
  • 33,793
  • 26
  • 129
  • 124
sibidiba
  • 5,974
  • 7
  • 35
  • 50