how to resize image with pillow in django

To resize an image with Pillow in Django, you can follow these steps:

  1. Install Pillow if you haven't already by running the command: pip install Pillow.

  2. Import the necessary modules in your Django views.py file: python from PIL import Image from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile

  3. Write a function to resize the image: python def resize_image(image, width, height): img = Image.open(image) img = img.resize((width, height), Image.ANTIALIAS) buffer = BytesIO() img.save(buffer, format='JPEG') buffer.seek(0) return InMemoryUploadedFile(buffer, None, image.name, 'image/jpeg', buffer.getbuffer().nbytes, None)

  4. In your view where you handle the form submission, call the resize_image function and save the resized image: python if request.method == 'POST': form = YourForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data['image'] resized_image = resize_image(image, 300, 300) # Replace 300 with your desired width and height # Save the resized image or use it as needed

Remember to replace YourForm with the actual name of your form. This code will resize the uploaded image to the specified dimensions using Pillow in Django.