首页 > 解决方案 > Django图像压缩和调整大小不起作用

问题描述

我不明白为什么这段代码不能调整图像大小?为什么图片上传的是实际大小?这是我的代码:

#models.py

from django.db import models
from PIL import Image
    
class Post(SafeDeleteModel):
             header_image = models.ImageField(upload_to="blog/images/", blank= True, null= True)
             
             def save(self,*args,**kwargs):
                  super().save(*args, **kwargs)
                  img = Image.open(self.header_image.path)
        
                  if img.height > 300 or img.width > 300:
                     out_put_size = (300,300)
                     img.thumbnail(out_put_size)
                     img.save(self.header_image.path)

#root urls.py

    urlpatterns = [
        path('admin/', admin.site.urls)
        path('',include('blog.urls')),
       
      
    ]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

#forms.py

class BlogPost(forms.ModelForm):
    class Meta:
      model = Post
      fields = ['title','author','body','header_image']
      
      widgets = {
         'title': forms.TextInput(attrs={'class':'form-control'}),
         'author': forms.Select(attrs={'class':'form-control'}),
         'body': RichTextField(),
      }

我的代码 .path未导入的屏幕截图。我认为这是主要问题 在此处输入图像描述

我的最终结果: 在此处输入图像描述

我也想知道如何在 django 模型中应用 PIL 的格式和质量属性。见下文:

("kenya_buzz_compressed.jpg", format="JPEG", quality=70)

标签: pythondjangopython-imaging-library

解决方案


如果要生成分辨率为 300x300 的图像,则必须在生成thumbnail()后对图像进行crop( )

def save(self, *args, **kwargs):
    super().save()
    img = Image.open(self.header_image.path)
    width, height = img.size  # Get dimensions
    print(f'Original Image Dimenstions: w:{width} h:{height}')

    if width > 300 and height > 300:
        # keep ratio but shrink down
        img.thumbnail((width, height))

    # check which one is smaller
    if height < width:
        # make square by cutting off equal amounts left and right
        left = (width - height) / 2
        right = (width + height) / 2
        top = 0
        bottom = height
        img = img.crop((left, top, right, bottom))

    elif width < height:
        # make square by cutting off bottom
        left = 0
        right = width
        top = 0
        bottom = width
        img = img.crop((left, top, right, bottom))

    if width > 300 and height > 300:
        img.thumbnail((300, 300))

    width, height = img.size  # Get new dimensions
    print(f'Cropped Image Dimenstions: w:{width} h:{height}')

    img.save(self.header_image.path)

推荐阅读