1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2012-today OpenERP s.a. (<http://openerp.com>).
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.
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.
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/>.
20 ##############################################################################
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]:
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)
43 def resize_image_big(base64_source, size=(1204, 1204), encoding='base64', filetype='PNG'):
44 return resize_image(base64_source, size, encoding, filetype, True)
46 def resize_image_medium(base64_source, size=(180, 180), encoding='base64', filetype='PNG'):
47 return resize_image(base64_source, size, encoding, filetype)
49 def resize_image_small(base64_source, size=(50, 50), encoding='base64', filetype='PNG'):
50 return resize_image(base64_source, size, encoding, filetype)