0

I'm trying to save a picture into a buffer. For that I'm using the following code:

import io
from PIL import Image
buffer = io.StringIO()
img = Image.open(<image_path>)
img = img.resize((640,960), Image.NEAREST)
format = "JPG" # JPG,PNG,etc.
img.save(buffer,format)

However, I get KeyError: 'JPG'. I've seen several answers using this approach, so I don't know why I'm getting this error. Here's an example.

An old man in the sea.
  • 1,169
  • 1
  • 13
  • 30

1 Answers1

1

The key error you are getting, is because you are passing the string 'JPG' as format.
JPG isn't a valid option in Pillow's format options. You want to use "JPEG" in this case.

Not passing format=variable in this case shouldn't matter, as format is a valid second positional argument.

Also, be careful. Format() is a builtin function in python. Currently you are overwriting that function with a string. It might be better to choose a different variable name, like 'frmt' or '_format'.

So, your code should work by changing the last 2 lines to the following:

frmt = "JPEG"
img.save(buffer,frmt)

or

frmt = "JPEG"
img.save(buffer,format=frmt)
Vvamp
  • 414
  • 4
  • 12