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

如何用前端JavaScript在发送至DALL·E API前验证图片

验证DALL·E API图片输入的最佳实践

核心验证项及实现方式

针对你需要验证的四个维度,推荐使用成熟的图像处理库(比如Python的Pillow)来完成,以下是具体实现逻辑:

1. 文件类型验证

DALL·E API仅支持JPEG、PNG、WEBP格式,不要仅依赖文件扩展名(可伪造),优先通过文件内容检测:

  • 用Pillow的Image.open()尝试打开文件,若抛出UnidentifiedImageError则说明格式不合法;
  • 也可通过读取文件头的魔术数字精准判断,避免扩展名欺骗。

2. 图片尺寸验证

API要求图片最短边≥256px,最长边≤2048px:

  • 打开图片后获取image.size(返回元组(宽度, 高度));
  • 计算最小边和最大边,分别与阈值对比。

3. 文件大小验证

API限制单张图片大小≤4MB:

  • 用os.path.getsize(file_path)获取文件字节数;
  • 判断是否≤4 * 1024 * 1024(即4MB)。

4. Alpha通道验证

DALL·E API不支持带Alpha通道的图片(透明背景):

  • 打开图片后检查image.mode属性,若为RGBA、LA或其他含Alpha的模式,则说明存在透明通道;
  • 若需兼容,可将图片转换为RGB模式(丢弃Alpha通道),但需提前告知用户。

完整代码示例(Python)

import os
from PIL import Image, UnidentifiedImageError

def validate_dalle_image(file_path):
    # 初始化错误信息列表
    errors = []

    # 1. 文件大小验证
    file_size = os.path.getsize(file_path)
    if file_size > 4 * 1024 * 1024:
        errors.append("文件大小超过4MB限制")

    try:
        # 2. 文件类型与基础合法性验证
        with Image.open(file_path) as img:
            # 验证支持的格式
            allowed_formats = {"JPEG", "PNG", "WEBP"}
            if img.format not in allowed_formats:
                errors.append(f"不支持的文件格式:{img.format},仅支持JPEG/PNG/WEBP")

            # 3. 尺寸验证
            width, height = img.size
            min_dim = min(width, height)
            max_dim = max(width, height)
            if min_dim < 256:
                errors.append(f"图片最短边{min_dim}px,需≥256px")
            if max_dim > 2048:
                errors.append(f"图片最长边{max_dim}px,需≤2048px")

            # 4. Alpha通道验证
            if img.mode in ("RGBA", "LA", "PA"):
                errors.append("图片包含Alpha通道,DALL·E API不支持透明背景")

    except UnidentifiedImageError:
        errors.append("无法识别的图片文件,格式可能损坏或不合法")
    except Exception as e:
        errors.append(f"验证出错:{str(e)}")

    return errors, len(errors) == 0

# 使用示例
file_path = "test_image.png"
errors, is_valid = validate_dalle_image(file_path)
if not is_valid:
    print("图片验证失败:")
    for err in errors:
        print(f"- {err}")
else:
    print("图片符合DALL·E API要求")

额外注意事项

  • 若需处理批量图片,可封装为批量验证函数,提高效率;
  • 转换Alpha通道时,img.convert("RGB")会默认将透明区域填充为白色,若需自定义背景色可指定参数;
  • 对于网络图片,需先下载到本地再执行上述验证步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:40:18