Django - 使用 Easy Thumbnails 时,即使提供了带 alpha 的 PNG,如何强制字段将缩略图转换为 JPG

Alv*_*ler 5 django django-rest-framework easy-thumbnails

当使用 Easy Thumbnails 时,我知道您可以通过将其添加到您的 settings.py 来全局配置所有图像(甚至带有 alpha 的 PNG)以转换为 JPG

THUMBNAIL_TRANSPARENCY_EXTENSION = 'jpg'
Run Code Online (Sandbox Code Playgroud)

但问题是我不想强制所有模型中的所有图像都转换为 JPG,因为我有一些模型需要带有 alpha (png) 的图像。

我想要的是强制单个模型中的单个字段将所有图像转换为 JPG,无论它们是否是启用了 Alpha 的 PNG。

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

我想要这个,因为很多人上传启用了 Alpha 的 PNG,这会阻止缩略图将它们压缩为 JPG,从而使许多缩略图保留为 PNG (500kb),而不是转换为 JPG (70kb)。

如何指定始终将这些文章图像转换为 JPG?

小智 1

您可以使用 PIL 进行转换和调整大小:

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
Run Code Online (Sandbox Code Playgroud)

然后在 save() 处你可以调用该函数:

''' 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
Run Code Online (Sandbox Code Playgroud)