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

调用OpenAI Image Edit API时持续返回400错误求助

排查OpenAI Image Edit API 400错误问题

核心错误原因

你直接将字符串文件名('maira.png'、'maira2.png')传入FormData的image和mask字段,但OpenAI Image Edit API要求这两个字段必须传入File/Blob对象,而非文件名字符串。

修正后的代码示例

假设你通过浏览器的文件输入框获取图片文件,代码调整如下:

// 页面需对应两个文件输入框,id分别为imageInput和maskInput
const imageInput = document.getElementById('imageInput');
const maskInput = document.getElementById('maskInput');

const form = new FormData();
// 从文件输入框提取File对象
form.append('image', imageInput.files[0]);
form.append('mask', maskInput.files[0]);
form.append('prompt', 'A sunlit indoor lounge area with a pool containing a flamingo');
form.append('n', '1');
form.append('size', '1024x1024');

fetch('https://api.openai.com/v1/images/edits', {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer YOUR_ACTUAL_API_KEY' // 替换为真实API密钥
    },
    body: form
})
.then(response => {
    if (!response.ok) {
        return response.json().then(err => { throw err; });
    }
    return response.json();
})
.then(data => console.log('响应结果:', data))
.catch(error => console.error('错误详情:', error));

额外检查项

  • API密钥验证:确保使用的是有效、未过期的OpenAI API密钥,Bearer后直接跟密钥字符串,不要保留占位符*myAPIKey*
  • 文件格式要求:图片和掩码必须是PNG格式,单文件大小不超过4MB,且两者的尺寸必须完全一致
  • 参数合法性:size仅支持256x256、512x512、1024x1024;n的取值范围为1-10(受账户权限限制)
  • 跨域问题:本地测试时不要直接打开HTML文件(file://协议),建议用本地服务器(如http-server)运行项目,避免CORS报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:45:41