generate-thumbnails-in-django-with-pil

To generate thumbnails in Django with PIL, follow these steps:

  1. Install the Python Imaging Library (PIL) by running the command pip install pillow in your terminal.

  2. Import the necessary modules in your Django project. Add the following lines at the top of your Python file:

from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
  1. Create a function that will generate the thumbnail. Here's an example:
def generate_thumbnail(image):
    # Open the image using PIL
    img = Image.open(image)

    # Calculate the aspect ratio of the image
    width, height = img.size
    aspect_ratio = width / height

    # Define the desired thumbnail size
    thumbnail_size = (100, int(100 / aspect_ratio))

    # Resize the image using PIL
    img.thumbnail(thumbnail_size)

    # Create a BytesIO object to store the thumbnail
    thumbnail_io = BytesIO()

    # Save the thumbnail to the BytesIO object in JPEG format
    img.save(thumbnail_io, format='JPEG')

    # Create an InMemoryUploadedFile from the BytesIO object
    thumbnail = InMemoryUploadedFile(
        thumbnail_io,
        None,
        'thumbnail.jpg',
        'image/jpeg',
        thumbnail_io.tell(),
        None
    )

    # Return the generated thumbnail
    return thumbnail
  1. In your Django view or model, call the generate_thumbnail function with the image file you want to generate a thumbnail for. For example:
def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():
            image = form.cleaned_data['image']
            thumbnail = generate_thumbnail(image)
            # Save the thumbnail or do something with it
    else:
        form = MyForm()
    return render(request, 'my_template.html', {'form': form})

That's it! By following these steps, you should be able to generate thumbnails in Django using PIL. Feel free to customize the code according to your specific requirements.