[FIX] tools.image: added an image conversion before sharpening; otherwise the filter...
[odoo/odoo.git] / openerp / tools / image.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2012-today OpenERP s.a. (<http://openerp.com>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import io
23 import StringIO
24
25 from PIL import Image
26 from PIL import ImageFilter
27 from random import random
28
29 # ----------------------------------------
30 # Image resizing
31 # ----------------------------------------
32
33 def image_resize_image(base64_source, size=(1024, 1024), encoding='base64', filetype='PNG', avoid_if_small=False):
34     """ Function to resize an image. The image will be resized to the given
35         size, while keeping the aspect ratios, and holes in the image will be
36         filled with transparent background. The image will not be stretched if
37         smaller than the expected size.
38         Steps of the resizing:
39         - if avoid_if_small: if both image sizes are smaller than the requested
40           sizes, the original image is returned. This is used to avoid adding
41           transparent content around images that we do not want to alter but
42           just resize if too big. This is used for example when storing images
43           in the 'image' field: we keep the original image, resized to a maximal
44           size, without adding transparent content around it if smaller.
45         - create a thumbnail of the source image through using the thumbnail
46           function. Aspect ratios are preserved when using it. Note that if the
47           source image is smaller than the expected size, it will not be
48           extended, but filled to match the size.
49         - create a transparent background that will hold the final
50           image.
51         - past the thumbnail on the transparent background and center
52           it.
53
54         :param base64_source: base64-encoded version of the source
55             image; if False, returns False
56         :param size: tuple(height, width)
57         :param encoding: the output encoding
58         :param filetype: the output filetype
59         :param avoid_if_small: do not resize if image height and width
60             are smaller than the expected size.
61     """
62     if not base64_source:
63         return False
64     image_stream = io.BytesIO(base64_source.decode(encoding))
65     image = Image.open(image_stream)
66     # check image size: do not create a thumbnail if avoiding smaller images
67     if avoid_if_small and image.size[0] <= size[0] and image.size[1] <= size[1]:
68         return base64_source
69     # create a thumbnail: will resize and keep ratios, then sharpen for better looking result
70     image.thumbnail(size, Image.ANTIALIAS)
71     image.convert('RGB')
72     image = image.filter(ImageFilter.SHARPEN)
73     # create a transparent image for background
74     background = Image.new('RGBA', size, (255, 255, 255, 0))
75     # past the resized image on the background
76     background.paste(image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
77     # return an encoded image
78     background_stream = StringIO.StringIO()
79     background.save(background_stream, filetype)
80     return background_stream.getvalue().encode(encoding)
81
82 def image_resize_image_big(base64_source, size=(1204, 1204), encoding='base64', filetype='PNG', avoid_if_small=True):
83     """ Wrapper on image_resize_image, to resize images larger than the standard
84         'big' image size: 1024x1024px.
85         :param size, encoding, filetype, avoid_if_small: refer to image_resize_image
86     """
87     return image_resize_image(base64_source, size, encoding, filetype, avoid_if_small)
88
89 def image_resize_image_medium(base64_source, size=(128, 128), encoding='base64', filetype='PNG', avoid_if_small=False):
90     """ Wrapper on image_resize_image, to resize to the standard 'medium'
91         image size: 180x180.
92         :param size, encoding, filetype, avoid_if_small: refer to image_resize_image
93     """
94     return image_resize_image(base64_source, size, encoding, filetype, avoid_if_small)
95
96 def image_resize_image_small(base64_source, size=(64, 64), encoding='base64', filetype='PNG', avoid_if_small=False):
97     """ Wrapper on image_resize_image, to resize to the standard 'small' image
98         size: 50x50.
99         :param size, encoding, filetype, avoid_if_small: refer to image_resize_image
100     """
101     return image_resize_image(base64_source, size, encoding, filetype, avoid_if_small)
102
103 # ----------------------------------------
104 # Colors
105 # ---------------------------------------
106
107 def image_colorize(original, randomize=True, color=(255, 255, 255)):
108     """ Add a color to the transparent background of an image.
109         :param original: file object on the original image file
110         :param randomize: randomize the background color
111         :param color: background-color, if not randomize
112     """
113     # create a new image, based on the original one
114     original = Image.open(io.BytesIO(original))
115     image = Image.new('RGB', original.size)
116     # generate the background color, past it as background
117     if randomize:
118         color = (int(random() * 192 + 32), int(random() * 192 + 32), int(random() * 192 + 32))
119     image.paste(color)
120     image.paste(original, mask=original)
121     # return the new image
122     buffer = StringIO.StringIO()
123     image.save(buffer, 'PNG')
124     return buffer.getvalue()
125
126 # ----------------------------------------
127 # Misc image tools
128 # ---------------------------------------
129
130 def image_get_resized_images(base64_source, return_big=False, return_medium=True, return_small=True,
131     big_name='image', medium_name='image_medium', small_name='image_small',
132     avoid_resize_big=True, avoid_resize_medium=False, avoid_resize_small=False):
133     """ Standard tool function that returns a dictionary containing the
134         big, medium and small versions of the source image. This function
135         is meant to be used for the methods of functional fields for
136         models using images.
137
138         Default parameters are given to be used for the getter of functional
139         image fields,  for example with res.users or res.partner. It returns
140         only image_medium and image_small values, to update those fields.
141
142         :param base64_source: base64-encoded version of the source
143             image; if False, all returnes values will be False
144         :param return_{..}: if set, computes and return the related resizing
145             of the image
146         :param {..}_name: key of the resized image in the return dictionary;
147             'image', 'image_medium' and 'image_small' by default.
148         :param avoid_resize_[..]: see avoid_if_small parameter
149         :return return_dict: dictionary with resized images, depending on
150             previous parameters.
151     """
152     return_dict = dict()
153     if return_big:
154         return_dict[big_name] = image_resize_image_big(base64_source, avoid_if_small=avoid_resize_big)
155     if return_medium:
156         return_dict[medium_name] = image_resize_image_medium(base64_source, avoid_if_small=avoid_resize_medium)
157     if return_small:
158         return_dict[small_name] = image_resize_image_small(base64_source, avoid_if_small=avoid_resize_small)
159     return return_dict