PIL Error Saving a JPEG Image
This bug has been very difficult to identify and workaround, so I’m writing this post for the record.
When I tried to save a JPEG encoded image using optimize option, I was getting the following error with some images:
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 100, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/motivator/../motivator/public/views.py", line 227, in creator_done_view
img.copy().resize((480, 480*h/w), Image.ANTIALIAS).save(fd, 'JPEG', optimize=True)
File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1439, in save
save_handler(self, fp, filename)
File "/usr/lib/python2.6/dist-packages/PIL/JpegImagePlugin.py", line 471, in _save
ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
File "/usr/lib/python2.6/dist-packages/PIL/ImageFile.py", line 501, in _save
raise IOError("encoder error %d when writing image file" % s)
IOError: encoder error -2 when writing image file
The weird thing is that it was happening with a couple of images, and I couldn’t find a pattern (although the image size seemed to be relevant).
The problem looks related to libjpeg (the library PIL is using) and the way PIL is encoding the JPEG, and after trying blindly to tweak the saving process, I managed to get it to work setting ImageFile.MAXBLOCK to a big value (by default it’s using 64KB).
# before saving, increase MAXBLOCK
from PIL import ImageFile
ImageFile.MAXBLOCK = 1024*1024
I don’t know what block size works best, because I certainly don’t know what kind of image is making PIL to crash, but 1MB it’s been working fine for me so far.
When I was looking for information about this bug I’ve found that there’s some people not very happy with PIL because of the JPEG support. It’s working OK for me now, but I’m not 100% happy with the workaround.