Skip to content

Instantly share code, notes, and snippets.

@jairajsahgal
Created September 30, 2023 18:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jairajsahgal/4a30efb080168116712b5cd85a721083 to your computer and use it in GitHub Desktop.
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.
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