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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.