HiAPI
博客

教程

通过 API 按精确尺寸生成产品图片:宽高比与电商平台规格

2026年11月3日
通过 API 按精确尺寸生成产品图片:宽高比与电商平台规格

每个销售渠道都要求你的产品图片采用不同的尺寸:Amazon 想要白底的大正方形图,Instagram 想要 4:5 的竖构图,Pinterest 想要 2:3 的 Pin 图,而你自己的店铺首页主视觉又需要超宽幅图片。本指南介绍如何用 hiapi API 以编程方式生成所有这些尺寸的图片——使用 gpt-image-2 和 wan2.7-image——以及如何每次都精确落到目标像素尺寸。

前置条件:一个 hiapi API 密钥(在 控制台 中创建),以及 curl 或 Python。总费用取决于你选择的模型和分辨率——参见 定价。

API 上的图片尺寸实际是怎么工作的

首先说最让人困惑的一点:hiapi 上的图片模型不接受像素尺寸。 没有 size、width 或 height 字段。如果你尝试传入,API 会明确告诉你:

{
  "code": 400,
  "error_code": "INVALID_REQUEST",
  "message": "invalid input: <root>: additional properties 'size' not allowed"
}

相反,尺寸由 input 中的两个字段控制:

  • aspect_ratio —— 画幅的形状,从每个模型固定的列表中选取。
  • resolution —— 输出档位:"1K"、"2K" 或 "4K"(长边大致为 1024 / 2048 / 4096 像素;精确像素数因比例而异,所以务必检查你拿到的文件)。

以下是本指南中两个模型实际接受的参数(已验证于线上 API):

gpt-image-2 wan2.7-image/text-to-image
prompt 必需 必需
aspect_ratio auto、1:1、3:2、2:3、4:3、3:4、5:4、4:5、16:9、9:16、2:1、1:2、3:1、1:3、21:9、9:21 —— 共 16 个值 1:1、16:9、4:3、21:9、3:4、9:16、8:1、1:8 —— 共 8 个值
resolution 1K、2K、4K 1K、2K、4K
额外能力 图生图变体(gpt-image-2/image-to-image) seed(整数)用于复现
像素 size / n 不接受 不接受

实际差别在于:gpt-image-2 覆盖了社交和电商平台格式所需的比例(4:5、2:3、5:4 为 gpt-image-2 独有),而 wan2.7-image 增加了 8:1/1:8 超宽条幅,其他比例列表都没有覆盖——适合窄条促销横幅——并且是 4K 棚拍图的常见选择。

因此,要精确控制尺寸,配方分两步:

  1. 用匹配的宽高比生成,并选择长边达到或超过目标尺寸的最小分辨率档位(之后缩小,永远不要放大)。
  2. 在本地把返回的文件调整到精确的目标像素——一行 Pillow 代码。

电商平台规格速查表

以下是常见公开的要求,映射到 API 参数:

渠道 典型目标 aspect_ratio resolution 模型备注
Amazon 主图 长边 ≥1000 像素(1600 像素以上可启用缩放),正方形,纯白背景 1:1 2K 两者皆可
Shopify 产品页 推荐 2048×2048 1:1 2K 两者皆可
Instagram 信息流(竖构图) 1080×1350 4:5 2K 仅 gpt-image-2
Stories / Reels / TikTok 1080×1920 9:16 2K 两者皆可
Pinterest Pin 1000×1500 2:3 2K 仅 gpt-image-2
Etsy 商品列表 推荐 2700×2025 4:3 4K 两者皆可(需 4K 档)
网站主视觉横幅 例如宽 2560 像素 21:9 4K 两者皆可
窄条促销横幅 超宽 8:1 2K/4K 仅 wan2.7-image

(各平台规格会变化;请将这些像素目标视为常见的公开推荐值,并以每个平台当前文档为准进行确认。)

最小可运行示例(curl)

一切都通过统一的异步任务端点运行:用 POST /v1/tasks 创建,用 GET /v1/tasks/<id> 轮询。创建一个 Amazon 风格的正方形图,使用 2K 档:

curl -s -X POST https://api.hiapi.ai/v1/tasks \
  -H "Authorization: Bearer sk-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2/text-to-image",
    "input": {
      "prompt": "Studio product photo of a stainless steel water bottle on a pure white background, centered, soft shadow, e-commerce catalog style",
      "aspect_ratio": "1:1",
      "resolution": "2K"
    }
  }'

响应中的任务 id 位于 data.taskId。轮询它:

curl -s https://api.hiapi.ai/v1/tasks/TASK_ID \
  -H "Authorization: Bearer sk-YOUR_KEY"

轮询直到 data.status 变为 "success"(或者 "fail",详细信息在 data.error 下)。图片 URL 位于 data.output[0].url。该 URL 会过期(输出对象带有 expireAt),所以应立即下载并重新托管到你自己的存储上——切勿在商品列表中直接热链。

生产脚本:一个产品,所有渠道,精确像素

这个批量脚本会预先创建所有任务(它们会在平台上并行运行),逐个轮询至完成,然后用 Pillow 调整到精确的目标尺寸。ImageOps.fit 一次调用即可同时处理缩小和任何细微裁剪。

import os
import time
from io import BytesIO

import requests
from PIL import Image, ImageOps

API = "https://api.hiapi.ai/v1"
HDRS = {
    "Authorization": f"Bearer {os.environ['HIAPI_KEY']}",
    "Content-Type": "application/json",
}

# 渠道 -> 生成参数 + 精确像素目标
SPECS = {
    "amazon-main":    {"model": "gpt-image-2/text-to-image", "aspect_ratio": "1:1",  "resolution": "2K", "px": (1600, 1600)},
    "shopify":        {"model": "gpt-image-2/text-to-image", "aspect_ratio": "1:1",  "resolution": "2K", "px": (2048, 2048)},
    "instagram-feed": {"model": "gpt-image-2/text-to-image", "aspect_ratio": "4:5",  "resolution": "2K", "px": (1080, 1350)},
    "story-reel":     {"model": "gpt-image-2/text-to-image", "aspect_ratio": "9:16", "resolution": "2K", "px": (1080, 1920)},
    "pinterest-pin":  {"model": "gpt-image-2/text-to-image", "aspect_ratio": "2:3",  "resolution": "2K", "px": (1000, 1500)},
    "etsy-listing":   {"model": "wan2.7-image/text-to-image", "aspect_ratio": "4:3",  "resolution": "4K", "px": (2700, 2025)},
    "hero-banner":    {"model": "wan2.7-image/text-to-image", "aspect_ratio": "21:9", "resolution": "4K", "px": (2560, 1097)},
}

PROMPT = (
    "Studio product photo of a stainless steel water bottle on a pure white "
    "background, centered, soft shadow, high detail, e-commerce catalog style"
)


def create_task(model: str, prompt: str, aspect_ratio: str, resolution: str) -> str:
    body = {
        "model": model,
        "input": {"prompt": prompt, "aspect_ratio": aspect_ratio, "resolution": resolution},
    }
    data = requests.post(f"{API}/tasks", json=body, headers=HDRS, timeout=60).json()
    task_id = (data.get("data") or {}).get("taskId")
    if not task_id:
        raise RuntimeError(f"create failed: {data}")
    return task_id


def wait_task(task_id: str, timeout_s: int = 600) -> str:
    deadline = time.time() + timeout_s
    while time.time() < deadline:
        data = requests.get(f"{API}/tasks/{task_id}", headers=HDRS, timeout=30).json()
        task = data.get("data") or {}
        if task.get("status") == "success":
            return task["output"][0]["url"]
        if task.get("status") == "fail":
            err = task.get("error") or {}
            raise RuntimeError(f"task {task_id} failed: {err.get('code')} {err.get('message')}")
        time.sleep(5)
    raise TimeoutError(f"task {task_id} did not finish in {timeout_s}s")


def save_exact(url: str, px: tuple, path: str) -> None:
    # 输出 URL 会过期 —— 立即下载,然后适配到精确像素。
    raw = requests.get(url, timeout=120).content
    img = Image.open(BytesIO(raw))
    ImageOps.fit(img, px, Image.LANCZOS).save(path)


if __name__ == "__main__":
    # 先创建所有任务:任务会在平台上并发运行
    tasks = {
        name: create_task(s["model"], PROMPT, s["aspect_ratio"], s["resolution"])
        for name, s in SPECS.items()
    }
    for name, task_id in tasks.items():
        url = wait_task(task_id)
        save_exact(url, SPECS[name]["px"], f"{name}.png")
        print(f"{name}: {SPECS[name]['px']} -> {name}.png")

即使你重写其余部分,也有两个细节值得照搬:

  • 选择分辨率档位时要保证长边 ≥ 目标。 Etsy 的 2700 像素目标超过了 2K 档的约 2048 像素,所以用 4K 生成再缩小。用 LANCZOS 缩小在商品目录用途上视觉无损;放大则不是。
  • 创建任务后立即持久化 taskId。 如果你的 worker 崩溃,恢复时轮询已存储的 id,而不是重新创建任务——重新创建会再生成(并计费)第二张图片。

改为重新排版一张已审核的主图

很多时候你并不想要七张独立生成的图——你想要的是同一张已审核的产品图,针对每个渠道重新构图。这就是 gpt-image-2/image-to-image:它需要 input_urls(一个可公开访问的图片 URL 数组)以及 prompt,并接受同样的 16 个 aspect_ratio 值:

{
  "model": "gpt-image-2/image-to-image",
  "input": {
    "prompt": "Extend the background naturally to fill the new frame; keep the product unchanged and centered",
    "input_urls": ["https://your-cdn.com/hero-shot.png"],
    "aspect_ratio": "9:16"
  }
}

相同的任务生命周期,最后同样走精确像素步骤。完整演练见 How to Use gpt-image-2 Image-to-Image via the hiapi API。

生产注意事项

用回调代替轮询。 对于服务器端,创建任务时传入顶层 callback,完全跳过轮询循环:

{
  "model": "gpt-image-2/text-to-image",
  "input": {"prompt": "...", "aspect_ratio": "1:1", "resolution": "2K"},
  "callback": {"url": "https://yourapp.com/hooks/hiapi", "when": "final"}
}

你会在最终状态收到一次 POST。把回调当作信号而非事实来源:行动前重新拉取 GET /v1/tasks/<id>,并按 taskId 去重。如果回调始终没到,请参阅 Why your hiapi task callback isn't firing。

错误处理。 认证失败返回 401 permission_denied——先检查 Authorization: Bearer sk-... 请求头。校验失败返回 400,并带 error_code: "INVALID_REQUEST",其消息特别有用:它会列出确切允许的值(上面的比例表就是这样验证的)。输入 schema 因模型而异——wan2.7-image 接受 seed,gpt-image-2 不接受;一些快速模型完全拒绝 resolution——所以硬编码字段前请查看每个模型的页面。

成本控制。 价格随模型和分辨率档位变化。迭代提示词时用 1K 生成,只在出终稿时切换到 2K/4K——当前的每张图片价格在 定价页面。

相关阅读

常见问题

我可以在请求中传入 1080×1350 这样的精确像素尺寸吗? 不行。size、width 和 height 会被以 400 拒绝(additional properties ... not allowed)。用匹配的 aspect_ratio 和等于或高于目标的 resolution 档生成,然后在本地缩小到精确像素——即上面的 Pillow 一行代码。

Amazon 主图该用什么设置? aspect_ratio: "1:1"、resolution: "2K",然后调整到你的目标尺寸(1600×1600 是可靠的默认值——高于 1000 像素的缩放阈值)。Amazon 主图还要求纯白背景,所以把它写进提示词,并在上架前审核输出。

我的目标比例不在列表中(例如 1.91:1 的链接广告格式)。怎么办? 用最接近的更宽或相等且完全覆盖目标的比例生成——对于 1.91:1,可用 2:1 或 16:9——然后居中裁剪。脚本中的 ImageOps.fit 正是这样做的:一次调用完成超出部分的裁剪和尺寸调整。

如何获得真正的 4K 产品图? 在两个模型上设置 resolution: "4K"。wan2.7-image 是 4K 棚拍风格图片的常见选择;提示词模式可参阅 Wan 2.7 电商指南。

生成的图片 URL 会过期吗? 会——每个输出都带有 expireAt。任务成功后立即下载文件并重新托管到你自己的存储。切勿把任务输出 URL 粘贴到商品列表中。

我可以在一次请求中生成多个变体吗? 不行——这些模型没有 n 参数。每张图片创建一个任务;任务并发运行,所以在循环中批量处理(如上文脚本)实际速度一样快。在 wan2.7-image 上,你可以改变 seed 来获得同一提示词的受控变体。

立即开始构建持久 AI 产物

获取 API 密钥,通过一个基于任务(task)的 API 调用图像、视频和音频模型。

阅读 API 文档