source: OpenRLabs-Git/deploy/rlabs-docker/web2py-rlabs/gluon/contrib/imageutils.py

main
Last change on this file was 42bd667, checked in by David Fuertes <dfuertes@…>, 4 years ago

Historial Limpio

  • Property mode set to 100755
File size: 2.3 KB
Line 
1# -*- coding: utf-8 -*-
2
3#######################################################################
4#
5# Put this file in yourapp/modules/images.py
6#
7# Given the model
8#
9# db.define_table("table_name", Field("picture", "upload"),
10#                 Field("thumbnail", "upload"))
11#
12# to resize the picture on upload
13#
14# from images import RESIZE
15#
16# db.table_name.picture.requires = RESIZE(200, 200)
17#
18# to store original image in picture and create a thumbnail
19# in 'thumbnail' field
20#
21# from images import THUMB
22# db.table_name.thumbnail.compute = lambda row: THUMB(row.picture, 200, 200)
23
24#########################################################################
25from gluon import current
26
27
28class RESIZE(object):
29
30    def __init__(self, nx=160, ny=80, quality=100, padding = False,
31                 error_message=' image resize'):
32        (self.nx, self.ny, self.quality, self.error_message, self.padding) = (
33            nx, ny, quality, error_message, padding)
34
35    def __call__(self, value):
36        if isinstance(value, str) and len(value) == 0:
37            return (value, None)
38        from PIL import Image
39        from io import BytesIO
40        try:
41            img = Image.open(value.file)
42            img.thumbnail((self.nx, self.ny), Image.ANTIALIAS)
43            s = BytesIO()
44            if self.padding:
45                background = Image.new('RGBA', (self.nx, self.ny), (255, 255, 255, 0))
46                background.paste(
47                    img,
48                    ((self.nx - img.size[0]) // 2, (self.ny - img.size[1]) // 2))
49                background.save(s, 'JPEG', quality=self.quality)
50            else:
51                img.save(s, 'JPEG', quality=self.quality)
52            s.seek(0)
53            value.file = s
54        except:
55            return (value, self.error_message)
56        else:
57            return (value, None)
58
59
60def THUMB(image, nx=120, ny=120, gae=False, name='thumb'):
61    if image:
62        if not gae:
63            request = current.request
64            from PIL import Image
65            import os
66            img = Image.open(os.path.join(request.folder, 'uploads', image))
67            img.thumbnail((nx, ny), Image.ANTIALIAS)
68            root, ext = os.path.splitext(image)
69            thumb = '%s_%s%s' % (root, name, ext)
70            img.save(request.folder + 'uploads/' + thumb)
71            return thumb
72        else:
73            return image
Note: See TracBrowser for help on using the repository browser.