将图片保存至缓冲区时触发KeyError: 'JPG'错误的排查求助
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.

