Login

Signal to resize uploaded Fiber images as new thumbnailed images

Author:
versae
Posted:
February 13, 2012
Language:
Python
Version:
1.3
Tags:
image thumbnail resize crop signal fiber
Score:
0 (after 0 ratings)

You only have to put the code in some of your models.py and to have django-fiber installed in your system. Every image uploaded using Fiber admin dialog will be automatically resized and thumbnailed. Or whatever you need to do with it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from os import path
from StringIO import StringIO
from PIL import Image as PILImage

from django.core.files.base import ContentFile
from django.db.models.signals import post_save
from django.dispatch import receiver

from fiber.models import Image


@receiver(post_save, sender=Image)
def resize_as_a_new_fiber_image(*args, **kwargs):
    im = kwargs.get("instance", None)
    max_width = 450
    max_height = 300
    if im.image.width > max_width or im.image.height > max_height:
        size =  (max_width, max_height)
        image = PILImage.open(im.image.path)
        xxx, image_name = path.split(im.image.path)
        if "." in image_name:
            image_name, extenstion = image_name.rsplit('.', 1)
            name = "%s_cropped.%s" % (image_name, extenstion)
        else:
            name = "%s_cropped" % image_name
        format = image.format
        if image.mode not in ("L", "RGB"):
            image = image.convert("RGB")
        resized_image = image.copy()
        resized_image.thumbnail(size, PILImage.ANTIALIAS)
        fp = StringIO()
        resized_image.save(fp, format, quality=128)
        cf = ContentFile(fp.getvalue())
        fiber_image = Image(title=im.title)
        fiber_image.image.save(name=name, content=cf, save=False)
        fiber_image.save()

More like this

  1. resize to thumbnail with scale-to-fill by rennat 6 years, 6 months ago
  2. Resize image on save by David 7 years ago
  3. Sharpening images by rajeshd 8 years, 1 month ago
  4. A Django form field that accepts an uploaded image and creates a resized image attached with a push-pin by rmisio 3 years, 11 months ago
  5. Updated Filter to resize a ImageField on demand (ver.2) by rawjam 5 years, 3 months ago

Comments

Please login first before commenting.