Google custom search for images only
Asked Answered
T

7

28

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.

Terrarium answered 9/12, 2011 at 16:44 Comment(0)
K
40

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.

Kiddy answered 2/10, 2012 at 19:26 Comment(4)
To do this you need to click "Enable image search" in your CSE console!Milamilady
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!Tipstaff
I think this is the documentation of parameters you can send, including searchType.P
Wow great, can you also kindly tell how to download this image or use it ?Catnip
C
6

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">**
Caldwell answered 26/1, 2013 at 17:14 Comment(0)
C
5

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.

Crabb answered 8/4, 2017 at 18:4 Comment(2)
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!Murguia
@Murguia 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 itCrabb
A
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. =)

Amandy answered 12/12, 2011 at 22:33 Comment(2)
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.Amandy
Why I'm curious about it is, that previously they do had a separate API for image search only.Terrarium
T
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

Terrarium answered 14/12, 2011 at 10:50 Comment(0)
I
2

Try adding this line:

customSearchOptions['disableWebSearch'] = true;
Introduction answered 4/6, 2012 at 16:20 Comment(0)
R
2

Try this one

customSearchOptions['searchType'] = "image"
customSearchOptions['enableImageSearch'] = true
customSearchOptions['disableWebSearch'] = true;
Responsion answered 4/6, 2015 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.