[ADD] tools.images: added function to resize images.
[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 from PIL import Image
24 import StringIO
25
26 def resize_image(base64_source, size=(1024, 1024), encoding='base64', filetype='PNG', avoid_if_small=False):
27     image_stream = io.BytesIO(base64_source.decode(encoding))
28     image = Image.open(image_stream)
29     # check image size: do not create a thumbnail if avoiding smaller images
30     if avoid_if_small and image.size[0] <= size[0] and image.size[1] <= size[1]:
31         return base64_source
32     # create a thumbnail: will resize and keep ratios
33     image.thumbnail(size, Image.ANTIALIAS)
34     # create a transparent image for background
35     background = Image.new('RGBA', size, (255, 255, 255, 0))
36     # past the resized image on the background
37     background.paste(image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
38     # return an encoded image
39     background_stream = StringIO.StringIO()
40     background.save(background_stream, filetype)
41     return background_stream.getvalue().encode(encoding)
42
43 def resize_image_big(base64_source, size=(1204, 1204), encoding='base64', filetype='PNG'):
44     return resize_image(base64_source, size, encoding, filetype, True)
45
46 def resize_image_medium(base64_source, size=(180, 180), encoding='base64', filetype='PNG'):
47     return resize_image(base64_source, size, encoding, filetype)
48     
49 def resize_image_small(base64_source, size=(50, 50), encoding='base64', filetype='PNG'):
50     return resize_image(base64_source, size, encoding, filetype)