Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a thumbnail Python Django

Tags:

python

django

#Model
class Article(models.Model):
   title = models.CharField(max_length=200, verbose_name='Name',)
   photo = models.ImageField(upload_to='news/%Y/%m/%d/', blank=True, 
   verbose_name='Image')

   def __str__(self):
        return self.title

   def get_absolute_url(self):
        return reverse('article', kwargs={'art_id': self.id})

How to make a thumbnail of the image, rename it to "* _thumb.jpg", and place it in the same directory where the file is saved?

like image 225
AeroFlow Avatar asked Jul 29 '26 08:07

AeroFlow


1 Answers

You can try this code:

import sys
from PIL import Image
from io import BytesIO
from django.db import models
from django.core.files.uploadedfile import InMemoryUploadedFile

class Article(models.Model):
    title = models.CharField(max_length=200, verbose_name='Name',)
    photo = models.ImageField(upload_to='news/%Y/%m/%d/', blank=True, 
    verbose_name='photo')
    thumbnails = models.ImageField(upload_to='news/thumbs/%Y/%m/%d/', blank=True, 
    verbose_name='thumbnails')

    def save(self, **kwargs):
        output_size = (300, 169)
        output_thumb = BytesIO()

        img = Image.open(self.photo)
        img_name = self.photo.name.split('.')[0]

        if img.height > 300 or img.width > 300:
            img.thumbnail(output_size)
            img.save(output_thumb,format='JPEG',quality=90)

        self.thumbnails = InMemoryUploadedFile(output_thumb, 'ImageField', f"{img_name}_thumb.jpg", 'image/jpeg', sys.getsizeof(output_thumb), None)

        super(Article, self).save()

Output will be like this:

enter image description here

N.B: My image file name was img_485x1000.jpg

like image 184
Sabil Avatar answered Jul 31 '26 22:07

Sabil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!