From 59ec75cbb0f1bc3385742134c03a85a111960ac7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thibault=20Delavall=C3=A9e?= Date: Wed, 27 Jun 2012 15:27:39 +0200 Subject: [PATCH] [ADD] tools.images: added function to resize images. bzr revid: tde@openerp.com-20120627132739-zdgvdqh2nbsfkyv7 --- openerp/tools/image.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/openerp/tools/image.py b/openerp/tools/image.py index 4dc92704c9f..edc251e40f6 100644 --- a/openerp/tools/image.py +++ b/openerp/tools/image.py @@ -18,3 +18,33 @@ # along with this program. If not, see . # ############################################################################## + +import io +from PIL import Image +import StringIO + +def resize_image(base64_source, size=(1024, 1024), encoding='base64', filetype='PNG', avoid_if_small=False): + image_stream = io.BytesIO(base64_source.decode(encoding)) + image = Image.open(image_stream) + # check image size: do not create a thumbnail if avoiding smaller images + if avoid_if_small and image.size[0] <= size[0] and image.size[1] <= size[1]: + return base64_source + # create a thumbnail: will resize and keep ratios + image.thumbnail(size, Image.ANTIALIAS) + # create a transparent image for background + background = Image.new('RGBA', size, (255, 255, 255, 0)) + # past the resized image on the background + background.paste(image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2)) + # return an encoded image + background_stream = StringIO.StringIO() + background.save(background_stream, filetype) + return background_stream.getvalue().encode(encoding) + +def resize_image_big(base64_source, size=(1204, 1204), encoding='base64', filetype='PNG'): + return resize_image(base64_source, size, encoding, filetype, True) + +def resize_image_medium(base64_source, size=(180, 180), encoding='base64', filetype='PNG'): + return resize_image(base64_source, size, encoding, filetype) + +def resize_image_small(base64_source, size=(50, 50), encoding='base64', filetype='PNG'): + return resize_image(base64_source, size, encoding, filetype)