Bedrock Runtime: InvokeModelWithResponseStream, https response error StatusCode:...
🚨 错误信息
🤖 AI解决方案
---
1. 错误翻译
原文:ValidationException: ....*.source.base64: image exceeds 5 MB maximum: 14759984 bytes > 5242880 bytes
译文:验证异常:图像大小超过 5 MB 上限:当前 14,759,984 字节 > 允许 5,242,880 字节
2. 原因分析
- 你的图像实际大小为 ~14.1 MB (14,759,984 字节),远超限制。
- 错误发生在调用
InvokeModelWithResponseStream API 时,服务端在验证请求参数阶段拒绝了请求。3. 解决方案
你需要在上传前对图像进行压缩或尺寸调整。
Python (PIL/Pillow库) 压缩示例:
python
from PIL import Image
import io
import base64def compress_and_encode_image(image_path, max_size_kb=4900, quality=85):
"""
压缩图像并返回Base64字符串
:param image_path: 图片路径
:param max_size_kb: 目标最大大小(KB),建议略低于5120KB以留出缓冲
:param quality: JPEG质量 (1-100)
:return: Base64编码字符串
"""
img = Image.open(image_path)
# 如果图像过大,可以先按比例缩小尺寸
max_pixels = 2048 # 根据你的需求调整
if max(img.size) > max_pixels:
ratio = max_pixels / max(img.size)
new_size = tuple(int(dim * ratio) for dim in img.size)
img = img.resize(new_size, Image.Resampling.LANCZOS)
# 转换为RGB模式(如果是RGBA)
if img.mode in ('RGBA', 'LA'):
background = Image.new('RGB', img.size, (255, 255, 255))
background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else img)
img = background
# 压缩循环,确保大小在限制内
buffer = io.BytesIO()
img.save(buffer, format='JPEG', quality=quality, optimize=True)
# 如果仍然太大,进一步降低质量
while len(buffer.getvalue()) > max_size_kb * 1024 and quality > 20:
quality -= 5
buffer = io.BytesIO()
img.save(buffer, format='JPEG', quality=quality, optimize=True)
# 返回Base64编码
return base64.b64encode(buffer.getvalue()).decode('utf-8')
使用示例
base64_image = compress_and_encode_image("your_image.jpg")
4. ️ 预防措施
1. 调整分辨率:大多数AI模型不需要极高分辨率图像(如超过2048px)。
2. 选择合适格式:优先使用JPEG(有损压缩)而非PNG(无损,文件较大)。
3. 批量处理:如果需要处理多张图片,实现自动化的压缩流水线。
- 本地工具:使用
imagemagick (CLI) 或在线压缩网站进行预处理。- 开发库:Python的
PIL/Pillow、Node.js的 sharp 库都是高效的图像处理选择。---
下次请