thumbnail an image

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from PIL import Image
import os.path
import StringIO

def thumbnail(filename, size=(50, 50), output_filename=None):
    image = Image.open(filename)
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')
    image = image.resize(size, Image.ANTIALIAS)

    # get the thumbnail data in memory.
    if not output_filename:
        output_filename = get_default_thumbnail_filename(filename)
    image.save(output_filename, image.format) 
    return output_filename

def thumbnail_string(buf, size=(50, 50)):
    f = StringIO.StringIO(buf)
    image = Image.open(f)
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')
    image = image.resize(size, Image.ANTIALIAS)
    o = StringIO.StringIO()
    image.save(o, "JPEG")
    return o.getvalue()
    
def get_default_thumbnail_filename(filename):
    path, ext = os.path.splitext(filename)
    return path + '.thumb.jpg'

More like this

  1. Admin Image Widget + easy-thumbnails by babu 2 years, 10 months ago
  2. Sharpening images by rajeshd 7 years, 1 month ago
  3. Image Standarization by garcia_marc 6 years ago
  4. Thumbnails in admin using django-thumbnails-works by dperetti 3 years, 4 months ago
  5. ImageField with specified maximum image size by virhilo 4 years, 1 month ago

Comments

Fredrik (on February 27, 2007):

To avoid extra copies, I'd recommend changing

image = Image.open(filename)
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)

to

image = Image.open(filename)
if image.mode not in ("L", "RGB"):
    image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)

The

image.save(file(output_filename, 'wb') ...

thing is also unnecessary; save() takes either a filename or a file object, so there's no need to open it yourself.

Cheers /F

#

marioparris (on June 7, 2007):

Also, change line 13 from: output_filename = get_default_thumbnail_filename(output_filename)

to: output_filename = get_default_thumbnail_filename(filename)

so it uses the filename of the file you are thumbnailing. If output_filename is None by default, then that causes a problem ;)

#

limodou (on August 2, 2007):

thanks to marioparris, I'v changed it.

#

dolilmao (on April 13, 2014):

I have been looking for somethink similar to this glad I found it

#

(Forgotten your password?)