Created
September 30, 2023 18:45
-
-
Save jairajsahgal/4a30efb080168116712b5cd85a721083 to your computer and use it in GitHub Desktop.
This gist contains a Django model for compressing images on save. The model can be used to save compressed images to a different directory, which can help to reduce the storage space required for your images and improve the performance of your website.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.db.models.signals import post_save | |
from django.dispatch import receiver | |
from PIL import Image | |
from io import BytesIO | |
from django.core.files.uploadedfile import InMemoryUploadedFile | |
class CompressedImage(models.Model): | |
original_image = models.ImageField(upload_to='images/') | |
compressed_image = models.ImageField(upload_to='images/compressed/', blank=True) | |
@receiver(post_save, sender=CompressedImage) | |
def compress_image_on_save(sender, instance, **kwargs): | |
if instance.original_image: | |
# Open the original image using Pillow | |
image = Image.open(instance.original_image.path) | |
# Compress the image using the provided function | |
compressed_image = compress_image(image) | |
# Create an in-memory buffer to save the compressed image | |
buffer = BytesIO() | |
compressed_image.save(buffer, format='JPEG') | |
# Save the compressed image to the compressed_image field | |
instance.compressed_image.save(instance.original_image.name, InMemoryUploadedFile( | |
buffer, None, instance.original_image.name, 'image/jpeg', buffer.tell(), None | |
), save=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment