How to compress image field in django?
To compress an image field in Django, follow these steps:
Import the necessary modules:
python from PIL import Image from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile
Define a function to compress the image:
python def compress_image(image): im = Image.open(image) output = BytesIO() im.save(output, format='JPEG', quality=60) output.seek(0) compressed_image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', output.getvalue(), None) return compressed_image
In your model, override the
save()
method: ```python from django.db import models
class MyModel(models.Model): image = models.ImageField(upload_to='images/')
def save(self, args, *kwargs):
if self.image:
self.image = compress_image(self.image)
super(MyModel, self).save(args, *kwargs)
```
- In your view or form, handle the image upload: ```python from django.shortcuts import render from .forms import MyForm
def upload_image(request): if request.method == 'POST': form = MyForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, 'success.html') else: form = MyForm() return render(request, 'upload.html', {'form': form}) ```
Note: Remember to replace MyModel
with the name of your model, and MyForm
with the name of your form.
By following these steps, you will be able to compress the image field in Django.