使用 django-resized 调整图像大小

问题描述

当图像上传到 AWS S3 时,我使用 django-resized 来减小图像的大小。

当图像宽于其高度时,调整大小工作正常。但是,当图像高度大于其宽度时,输出图像将旋转 90 度且其宽度大于其高度。

models.py

from django_resized import ResizedImageField

class Catch(models.Model):
    fish_type = models.CharField("Fish Type",max_length=50,choices=fish_choices,default="Carp")
    catch_id = models.AutoField(primary_key=True)
    weight = models.DecimalField("Weight",max_digits=5,decimal_places=2)
    length = models.DecimalField("Length",decimal_places=2,blank=True,null=True)
    datetime = models.DateTimeField("Catch Time",auto_Now=False,auto_Now_add=False)
    image = ResizedImageField(size=[1080,1350],quality=95,null=True,default="default_img.png",upload_to="catch_images/")
    fisherman = models.ForeignKey(Fisherman,on_delete=models.CASCADE)
    trip = models.ForeignKey(Trips,on_delete=models.CASCADE)
    hookbait_name = models.CharField('Csali megnevezése',max_length=120,null=True)
    hookbait = models.ForeignKey(HookBait,on_delete=models.SET_NULL,null=True)

settings.py

DJANGORESIZED_DEFAULT_KEEP_Meta = True
DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG'
DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"}
DJANGORESIZED_DEFAULT_norMALIZE_ROTATION = True

我只想在保留纵横比的同时减小图像的大小。

在此先感谢您的帮助。

编辑!

我自己设法解决了这个问题。我使用枕头调整图像大小,但我还必须根据方向标签旋转它们。

正确的代码在这里

models.py

from PIL import Image,ExifTags
from io import BytesIO
from django.core.files import File

class Catch(models.Model):
    fish_type = models.CharField("Fish Type",auto_Now_add=False)
    image = models.ImageField(null=True,null=True)

    class Meta:
        verbose_name = "Catch"
        verbose_name_plural = "Catches"
    
    def save(self,*args,**kwargs):
        if self.image:
            img = Image.open(BytesIO(self.image.read()))
            
            if hasattr(img,'_getexif'):
                exif = img._getexif()
                if exif:
                    for tag,label in ExifTags.TAGS.items():
                        if label == 'Orientation':
                            orientation = tag
                            break
                    if orientation in exif:
                        if exif[orientation] == 3:
                            img = img.rotate(180,expand=True)
                        elif exif[orientation] == 6:
                            img = img.rotate(270,expand=True)
                        elif exif[orientation] == 8:
                            img = img.rotate(90,expand=True)

            img.thumbnail((1080,1080),Image.ANTIALIAS)
            output = BytesIO()
            img.save(output,format='JPEG',quality=95)
            output.seek(0)
            self.image = File(output,self.image.name) 

        return super().save(*args,**kwargs)

解决方法

为此您应该使用 PIL/pillow。像这样编辑您的模型,所有图像将在保存到数据库之前调整大小。

你可以这样做:

from PIL import Image as Img
import io
from django.core.files.uploadhandler import InMemoryUploadedFile

class Catch(models.Model):
   #rest fields here
   image=models.ImageField(upload_to='Media/Users')

   def save(self):
      if self.image:
          img = Img.open(io.BytesIO(self.image.read()))
          if img.mode != 'RGB':
              img = img.convert('RGB')
          img.thumbnail((100,100),Img.ANTIALIAS)  #(width,height)
          output = io.BytesIO()
          img.save(output,format='JPEG')
          output.seek(0)
          self.image= InMemoryUploadedFile(output,'ImageField',"%s.jpg" 
                      %self.image.name.split('.')[0],'image/jpeg',"Content- 
                      Type: charset=utf-8",None)
      super(Catch,self).save()

注意:thumbnail 函数还可以减小图像的大小。在这里,我为输出图像提供了 100 像素的宽度和高度。只需根据您的要求更改元组值 (width,height)

此外,如果您只想调整图像大小,您可以使用 resize 函数代替 thumbnail