我构建了这个基于任何查询的脚本,它通过使用 google 客户搜索 api 来提取它找到的第一个 google 图像。它工作正常,但往往会拉出低质量的图像。如何增强此代码,使其提取具有一定像素数或更高质量的图像?
我的代码可以在这里找到:https://codepen.io/Julienw2/pen/OJoaMEO
我相信也许这部分可以调整一些东西,但我真的不知道:
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, searchTerm);
};
x.onerror = function() {
errorCallback('Network error.');
};
x.send();
}
基于自定义搜索docs,看起来您无法真正根据像素密度来定位图像。但是,有
imgSize
查询参数。您可以在 searchUrl 中包含 imgSize=large
以仅搜索大图像,这些图像通常质量较高。
您可以在这里找到更多信息: https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list#body.QUERY_PARAMETERS.img_size
我希望这有帮助。