Field compute= and make thumbnail

89 views
Skip to first unread message

Pepe Araya

unread,
Sep 26, 2011, 1:06:14 PM9/26/11
to web...@googlegroups.com
Hello,

I have a table where only store images related to x Article. 

db_define_table('images',
      Field('original_image', 'upload'),
      Field('thumb_image', 'upload')

Is efficient even, possible to make  'thumb_image' Field a computed Field?
Something like:

      Field('thumb_image', 'upload', compute= lambda r:make_thumb(r, 85))


def make_thumb(r, thumb_size):

    try:
        from PIL import Image
    except:
        raise ImportError, "Requires PIL installed in your system."


    size = (thumb_size, thumb_size)
    ....

Any help is welcome!

thanks!

Anthony

unread,
Sep 26, 2011, 1:53:23 PM9/26/11
to web...@googlegroups.com
See http://www.web2pyslices.com/main/slices/take_slice/62 (also, look at the comments on that post for additional options).
 
Anthony

pbreit

unread,
Sep 26, 2011, 2:30:14 PM9/26/11
to web...@googlegroups.com
Here's what I do. Seems to work.

    Field('image', 'upload', uploadfolder=request.folder+'static/uploads',
            requires=IS_EMPTY_OR(IS_IMAGE())),
    Field('image_display', 'upload', uploadfolder=request.folder+'static/uploads',
            compute=lambda r: resize_image(r['image'], (320,320), 'display'),
            readable=False, writable=False),
    Field('image_thumb', 'upload', uploadfolder=request.folder+'static/uploads',
            compute=lambda r: resize_image(r['image'], (150,130), 'thumb'),
            readable=False, writable=False),

def resize_image(image, size, path, rotate=0):
    import os.path
    from PIL import Image'
    if image:
        try:
            img = Image.open('%sstatic/uploads/%s' % (request.folder, image))
            img = img.convert("RGB")
            img.thumbnail(size, Image.ANTIALIAS)
            img = img.rotate(rotate)
            root, ext = os.path.splitext(image)
            filename = '%s_%s%s' %(root, path, ext)
            img.save('%sstatic/uploads/%s' % (request.folder, filename))
            return filename
        except Exception, e:
            return e
    else:
        return None

Pepe Araya

unread,
Sep 26, 2011, 10:29:32 PM9/26/11
to web...@googlegroups.com
oh! thanks very much!

I'll try

pepe
Reply all
Reply to author
Forward
0 new messages