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

将图片保存至缓冲区时触发KeyError: 'JPG'错误的排查求助

Fixing KeyError: 'JPG' When Saving PIL Image to Buffer

Hey there! Let's work through that KeyError issue you're hitting. The problem comes from two small, easy-to-miss mistakes in your code—here's how to fix them:

1. Wrong Format Identifier

PIL's save() method expects the standard format name for image types, not the common file extension. For JPEG images, you need to use 'JPEG' instead of 'JPG'. While .jpg is a valid file extension, PIL internally recognizes the official format string 'JPEG'.

2. Using the Wrong Buffer Type

io.StringIO() is designed for text data, but image files are binary. You should use io.BytesIO() instead to handle the binary data from the resized image. Using StringIO here will cause issues even if you fix the format error, since it can't properly store binary content.

Corrected Code

Here's your code with both fixes applied:

import io
from PIL import Image

# Use BytesIO instead of StringIO for binary image data
buffer = io.BytesIO()
img = Image.open("<image_path>")
img = img.resize((640, 960), Image.NEAREST)
# Use 'JPEG' instead of 'JPG' as the format identifier
format = "JPEG"  # JPEG, PNG, etc.
img.save(buffer, format)

# Optional: Reset buffer pointer to the start if you need to read from it later
buffer.seek(0)

Quick Tip

If you want to avoid hardcoding the format, you can grab the original format from the opened image with img.format (this will return 'JPEG' for .jpg files, 'PNG' for .png, etc.):

format = img.format
img.save(buffer, format)

That should resolve the KeyError and get your image saving to the buffer correctly!

内容的提问来源于stack exchange,提问作者An old man in the sea.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 23:42:37