status_code=400, Image 0 failed: Image exceeds the maximum allowed total pixels....
错误信息
status_code=400, Image 0 failed: Image exceeds the maximum allowed total pixels. Current dimensions: 13x172574788 = 2243472244 pixels. Maximum allowed: 36000000 pixels. Request id: 0217835146831284f01ec66621d0980a42fd45436ed759587045f
AI 解决方案
🔍 报错分析
1. 🌐 错误翻译
原文:status_code=400, Image 0 failed: Image exceeds the maximum allowed total pixels. Current dimensions: 13x172574788 = 2243472244 pixels. Maximum allowed: 36000000 pixels. Request id: 0217835146831284f01ec66621d0980a42fd45436ed759587045f
译文:状态码=400,图片0失败:图片超出允许的最大总像素数。当前尺寸:13x172574788=2243472244像素。最大允许:36000000像素。请求ID:0217835146831284f01ec66621d0980a42fd45436ed759587045f
2. 🎯 原因分析
根本原因:图片的像素总数严重超出了API接口的像素限制。
当前图片总像素高达2,243,472,244像素,远超API允许的36,000,000像素上限。问题出在图片的一个维度异常大(宽度仅13,但高度高达172,574,788),导致像素总数超标。
3. 💡 解决方案
需要对图片进行压缩或裁剪,确保总像素≤36000000。以下是使用Python和PIL库的修复方案:
from PIL import Image
import io
def resize_image_to_max_pixels(image_path, max_pixels=36000000):
"""
调整图片尺寸,确保总像素不超过最大限制
"""
with Image.open(image_path) as img:
width, height = img.size
current_pixels = width * height
# 如果像素数未超标,直接返回原图
if current_pixels <= max_pixels:
return img
# 计算缩放比例,保持宽高比
scale = (max_pixels / current_pixels) ** 0.5
new_width = int(width * scale)
new_height = int(height * scale)
# 确保新尺寸的像素数不超过限制
while new_width * new_height > max_pixels and new_width > 0 and new_height > 0:
if new_width > new_height:
new_width -= 1
else:
new_height -= 1
# 重新调整尺寸
resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
return resized_img
# 使用示例
input_path = "your_image.jpg" # 替换为你的图片路径
resized_image = resize_image_to_max_pixels(input_path)
# 保存或继续处理
resized_image.save("resized_image.jpg")
替代方案:如果图片尺寸异常大,也可以直接裁剪:
def crop_image_to_max_pixels(image_path, max_pixels=36000000):
with Image.open(image_path) as img:
width, height = img.size
current_pixels = width * height
if current_pixels <= max_pixels:
return img
# 计算最大允许尺寸(保持原宽高比)
max_width = int((max_pixels * width / height) ** 0.5)
max_height = max_pixels // max_width
# 裁剪到合适尺寸
return img.resize((max_width, max_height), Image.Resampling.LANCZOS)
4. 🛡️ 预防措施
- 📏 图片预处理:在发送API请求前,主动检查图片像素,确保符合API限制。可封装检查函数:
def check_image_pixels(img, max_pixels=36000000):
width, height = img.size
return width * height <= max_pixels
Image.size属性,在代码中添加预检查逻辑;也可使用命令行工具file或identify快速查看图片尺寸。