You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Custom Search API中指定X Large及以上尺寸的图片?

解决Google Custom Search API获取XL及以上尺寸图片的问题

我之前做图片搜索项目时也碰到过一模一样的问题,Google Custom Search API 的 imgSize 参数确实没直接支持“大于等于某尺寸”的选项,但有几个实用的办法能实现需求:

1. 多请求合并去重

虽然API不允许同时指定多个imgSize值,但你可以分别发起三次请求,分别传入imgSize=xlarge、imgSize=xxlarge、imgSize=huge,然后把返回的结果合并,再通过图片的image.id或link字段去重,避免重复内容。

示例伪代码:

# 伪代码示例
import requests

API_KEY = "你的API密钥"
CX = "你的搜索引擎ID"
SEARCH_QUERY = "你的搜索关键词"

target_sizes = ["xlarge", "xxlarge", "huge"]
final_results = []
processed_image_ids = set()

for size in target_sizes:
    api_url = f"https://www.googleapis.com/customsearch/v1?q={SEARCH_QUERY}&cx={CX}&key={API_KEY}&searchType=image&imgSize={size}"
    response = requests.get(api_url).json()
    if "items" in response:
        for item in response["items"]:
            img_unique_id = item["image"]["id"]
            if img_unique_id not in processed_image_ids:
                processed_image_ids.add(img_unique_id)
                final_results.append(item)

# final_results 就是合并去重后的XL及以上尺寸图片集合

2. 本地筛选图片尺寸

Google Custom Search API 返回的每个图片结果里,都会携带image.width和image.height属性。你可以先请求imgSize=xlarge(甚至不指定尺寸,返回全量结果),然后在本地筛选出宽度或高度达到XL标准的图片。

根据Google官方定义:

  • X Large:宽度≥1600px 或 高度≥1600px
  • XX Large:宽度≥2000px 或 高度≥2000px
  • Huge:宽度≥3000px 或 高度≥3000px

所以设置筛选阈值为宽度≥1600px 或 高度≥1600px,就能覆盖所有XL及以上的图片:

示例伪代码:

# 伪代码示例
import requests

API_KEY = "你的API密钥"
CX = "你的搜索引擎ID"
SEARCH_QUERY = "你的搜索关键词"

api_url = f"https://www.googleapis.com/customsearch/v1?q={SEARCH_QUERY}&cx={CX}&key={API_KEY}&searchType=image"
response = requests.get(api_url).json()

filtered_images = []
if "items" in response:
    for item in response["items"]:
        img_w = item["image"]["width"]
        img_h = item["image"]["height"]
        # 筛选XL及以上尺寸的图片
        if img_w >= 1600 or img_h >= 1600:
            filtered_images.append(item)

# filtered_images 就是符合要求的图片列表

3. 结合可编程搜索引擎后台设置

如果你用的是Google Programmable Search Engine(原Custom Search Engine),可以在后台的「图片搜索设置」里,把默认尺寸设为“X Large”,这样API返回的结果本身就以大尺寸为主,再配合上面的本地筛选方法,能减少需要处理的结果数量,效率更高。

不过要注意,后台设置的默认尺寸只是优先返回该尺寸,不会完全排除更大的图片,保险起见还是加上本地筛选,确保不会漏掉XXL和Huge尺寸的内容。

内容的提问来源于stack exchange,提问作者TinyTiger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:14:00