[IMP] don't reimplement randint manually
[odoo/odoo.git] / openerp / tools / image.py
index b2feffa..d6a9e3b 100644 (file)
 #
 ##############################################################################
 
-import io
-import StringIO
+try:
+    import cStringIO as StringIO
+except ImportError:
+    import StringIO
 
 from PIL import Image
-from PIL import ImageEnhance, ImageOps
-from random import random
+from PIL import ImageOps
+from random import randint
 
 # ----------------------------------------
 # Image resizing
@@ -64,7 +66,7 @@ def image_resize_image(base64_source, size=(1024, 1024), encoding='base64', file
         return False
     if size == (None, None):
         return base64_source
-    image_stream = io.BytesIO(base64_source.decode(encoding))
+    image_stream = StringIO.StringIO(base64_source.decode(encoding))
     image = Image.open(image_stream)
 
     asked_width, asked_height = size
@@ -74,9 +76,16 @@ def image_resize_image(base64_source, size=(1024, 1024), encoding='base64', file
         asked_height = int(image.size[1] * (float(asked_width) / image.size[0]))
     size = asked_width, asked_height
 
-    background = ImageOps.fit(image, size, Image.ANTIALIAS)
+    # 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
+
+    if image.size != size:
+        # If you need faster thumbnails you may use use Image.NEAREST
+        image = ImageOps.fit(image, size, Image.ANTIALIAS)
+
     background_stream = StringIO.StringIO()
-    background.save(background_stream, filetype)
+    image.save(background_stream, filetype)
     return background_stream.getvalue().encode(encoding)
 
 def image_resize_image_big(base64_source, size=(1204, 1204), encoding='base64', filetype='PNG', avoid_if_small=True):
@@ -111,11 +120,11 @@ def image_colorize(original, randomize=True, color=(255, 255, 255)):
         :param color: background-color, if not randomize
     """
     # create a new image, based on the original one
-    original = Image.open(io.BytesIO(original))
+    original = Image.open(StringIO.StringIO(original))
     image = Image.new('RGB', original.size)
     # generate the background color, past it as background
     if randomize:
-        color = (int(random() * 192 + 32), int(random() * 192 + 32), int(random() * 192 + 32))
+        color = (randint(32, 224), randint(32, 224), randint(32, 224))
     image.paste(color)
     image.paste(original, mask=original)
     # return the new image