[Image-SIG] some trouble about jpeg encode in PIL

Fredrik Lundh fredrik at pythonware.com
Fri Oct 27 11:53:41 CEST 2006

"feihu_roger" wrote:

> I use PIL to thumbnail and save one jpeg. raise one IOException:
> >>> im= Image.open('e:/11.jpg')
> >>> im.thumbnail((600,600))
> >>> im.save('e:/11_m.jpg', 'JPEG', quality=90,progressive=1)
> Traceback (most recent call last):
>   File "<pyshell#74>", line 1, in -toplevel-
>    im.save('e:/11_m.jpg', 'JPEG',   quality=90,progressive=1)
>  File "D:\dev\Python24\Lib\site-packages\PIL\Image.py", line 1305, in save
>    save_handler(self, fp, filename)
>  File "D:\dev\Python24\lib\site-packages\PIL\JpegImagePlugin.py", line 409, in _save
>    ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
>  File "D:\dev\Python24\Lib\site-packages\PIL\ImageFile.py", line 491, in _save
>    raise IOError("encoder error %d when writing image file" % s)
> IOError: encoder error -2 when writing image file

this is a known limitation; PIL uses the JPEG library's incremental encoding mode, but
that doesn't work right in combination with progressive encoding, when the image is too
large.  to work around this, you can

1. fallback on non-progressive encoding when you get the above error

        im.save(outfile, quality=90, progressive=1)
    except IOError:
        im.save(outfile, quality=90) # retry in non-progressive mode


2. tweak the ImageFile.MAXBLOCK value before you save the image; you can either
simply set it to something reasonably large (e.g. 256*1024 or even 1024*1024) up front:

     import ImageFile

     ImageFile.MAXBLOCK = 1024*1024

or bump the size only if you get the above error.


More information about the Image-SIG mailing list