PIL thumbnails unreasonably large

Fredrik Lundh fredrik at pythonware.com
Wed May 10 11:25:44 EDT 2006


Almad wrote:

> I wonder how do I create reasonable thumbnails from JPEG with PIL.
> My code:
>
>             logging.debug('Downloading image %s' % id)
>             uri = ''.join([config['photo']['masterpath'], '?p=',
> str(id)])
>             uf = urlopen(uri).read()
>             f = tmpfile()
>             f.write(uf)
>             f.seek(0)
>             logging.debug('Resizing image %s' % id)
>             img = Image.open(f)
>             prev = img.copy()
>             img.thumbnail((180,180))
>             if prev.size[0] > 640 or prev.size[1] > 640:
>                 prev.thumbnail((640,640))
>             # save resized to temporary files
>             f.seek(0)
>             img.save(f, "JPEG", quality=50)
>             fp = tmpfile()
>             prev.save(fp, "JPEG", quality=200)
>
> Well, works fine, but img size is about 0,5 MB (!), but strangely, prev
> one is around 200 kb.

seek(0) doesn't truncate the file.  if you want a small thumbnail file, you
shouldn't write it to the beginning of a large file.

try calling the truncate method after you've saved the file:

    img.save(f, "JPEG", quality=50)
    f.truncate()

(a better solution would be to wrap the data in a StringIO object, and
write the thumbnail into a fresh temp file -- or another StringIO object:

    uf = urlopen(uri).read()
    img = Image.open(StringIO.StringIO(uf))
    ...
    f = tmpfile()
    img.save(f, "JPEG")
    ...

)

</F>






More information about the Python-list mailing list