4

When using Easy Thumbnails I'm aware that you can globally configure for all images (even PNGs with alpha) to be converted to JPG by adding this to your settings.py

THUMBNAIL_TRANSPARENCY_EXTENSION = 'jpg'

But the problem is that I don't want to force ALL of my images in all t he models to be converted to JPG because I have some models that require images with alpha (png).

What I want is to force a single field in a single model to convert to JPG all images no matter if they are PNGs with alpha enabled.

class Article(BaseModel):
    title = models.CharField(max_length=255, unique=True)
    image = ThumbnailerImageField(upload_to='blog/articles/image')

I want this because many people are uploading PNG's with alpha enabled and this is preventing the Thumbnailer to compress them as JPG making many of the thumbnails remain as PNG's (500kb) instead of being converted to JPG (70kb).

How can I specify to always convert these article images to JPG?

Alvaro Bataller
  • 487
  • 8
  • 29

1 Answers1

1

You can use PIL to convert and resize:

from PIL import Image

def image_resize(image, tgt_width):
    img = Image.open(image)
    width, height = img.size
    ratio = width / height
    tgt_height = int(tgt_width / ratio)
    img = img.resize((tgt_width, tgt_height), Image.ANTIALIAS)
    if tgt_height > tgt_width:
        # Crop from top to get desired height and make it square
        top = 0
        bottom = tgt_width
        img = img.crop((0, top, tgt_width, bottom))
    img = img.convert('RGB')
    return img

Then at save() you can call the function:

''' Your model with a your_model_image file field'''
def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    if self.your_model_image:
        img_path = self.your_model_image.path
        print(str(img_path))
        img = image_resize(img_path, 200) # Here you can predefine the width 
        # or even modify the above function to state width AND height
        new_img_path = img_path.split('.')[0]+'.jpg'
        os.remove(img_path)
        img.save(new_img_path, format='JPEG', quality=100, optimize=True)
        self.your_model_image = new_img_path
        super().save(*args, **kwargs)
    elif self.your_model_image == None:
        pass
Victor Donoso
  • 411
  • 2
  • 9
  • Thanks for your reply but this removes the functionality of Easy Thumbnails in Django, I want to keep that functionality and just force the image to be converted to JPG instead of PNG – Alvaro Bataller Mar 20 '23 at 21:51