python - 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(),
}
我也想知道如何在 django 模型中应用 PIL 的格式和质量属性。见下文:
("kenya_buzz_compressed.jpg", format="JPEG", quality=70)
解决方案
如果要生成分辨率为 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)
推荐阅读
- javascript - 如何在动态组件标签内重用vue中的组件?
- javascript - 基于 JSON 对象时如何使用 ASP 更新 URL 地址
- assembly - 两个输入并将它们相乘。如何做到这一点?
- react-native - 反应原生图像背景不是全屏
- discord - 是否可以在不和谐中使用功能性前缀文本?像悬停或可点击
- c - C - memcpy with char * 长度大于源字符串长度
- sql - 如何创建从表中读取的动态视图?
- excel - 如何使用 Office JS API 在 Excel 中对行或列进行分组
- git - 您的分支领先于“origin/foobranch” N 次提交 - 什么提交?
- drake - 在 Ubuntu 18.04 上本地安装 Drake 的问题