python - 使用 Pillow 在图像上传 Django 2 上调整大小和创建缩略图
问题描述
我正在尝试在上传时调整图像大小,并使用相同大小的图像创建缩略图。我以前能够毫无问题地调整图像大小,但是,当我尝试添加缩略图功能时,我无法让它工作。我查看了所有其他相关问题,所有这些问题要么已经过时,要么在我的情况下没有用。
模型.py
class Project(models.Model):
cover_image=models.ImageField(max_length=150, upload_to='project-covers/', default='Default.png', null=True)
thumbnail=models.ImageField(max_length=150, upload_to='project-thumbnails/', null=True)
def save(self, *args, **kwargs):
# pdb.set_trace()
if self.cover_image:
fname = self.title + '_cover.'
tname = self.title + '_thumbnail.'
self.resizeUploadedImage(fname)
self.createThumbnail(tname)
super(Project, self).save(*args, **
def resizeUploadedImage(self, fname):
'''Resize the image being uploaded.'''
try:
im = Image.open(self.cover_image)
if im.width > IMAGE_SIZE[0] or im.heght > IMAGE_SIZE[1]:
im.resize(IMAGE_SIZE, Image.ANTIALIAS)
image_io = BytesIO()
im.save(image_io, im.format)
# pdb.set_trace()
fname = fname + im.format
self.cover_image.save(fname, ContentFile(image_io.read(), False))
im.close()
image_io.close()
except IOError as e:
print("Could not resize image for", self.image)
print(e)
def createThumbnail(self, fname):
'''Create thumbnail of the image.'''
try:
if self.thumbnail is None:
im = Image.open(self.cover_image)
im.thumbnail(THUMB_SIZE)
image_io = BytesIO()
im.save(image_io, im.format)
fname = fname + im.format
self.thumbnail.save(fname, ContentFile(image_io.getvalue(), False))
im.close()
except IOError as e:
print('Could not create a thumbnail for', self.image)
print(e)
最初我使用 resizeUploadedImage 和 createThumbnail 方法并成功调整大小,但缩略图在我的管理页面和数据库上始终为空。在缩略图上有“editable=False”之前,因为我希望它在幕后自动创建。我认为这可能会阻止更改,所以我将其取出,但它并没有改变结果。
然后我尝试将两者都移到保存方法中(因为我之前在将调整大小移到保存之外时遇到了问题),但它仍然无法正常工作。
我在几个文档中看到最好将 super() 调用放在 save 方法的末尾,但是当我这样做时,我得到了
UNIQUE constraint failed: projects_project.id
如何从 cover_image 创建缩略图并将其保存到缩略图字段?
PS 在运行./manage.py test projects
时,它似乎实际上是在将文件保存到我的磁盘上,我认为这是不应该发生的,所以我认为我的 Pillow 代码存在某种问题。我最终得到 '1_cover.PNG'、'1Project0_cover.PNG'、'1Project1_cover.PNG'、'2_cover.PNG' 等,等等,即使我的 setuptestdata 只有“项目 1”,也计数到 9。
PPS 我在某处读到,最好使用 Pillow 的缩略图功能来调整大小,因为它会保持纵横比,而调整大小不会。有人对此有任何见解吗?
解决方案
from PIL import Image
def save(self):
super().save()
img = Image.open(self.cover_image.path)
if img.height > 250 or img.width > 250:
output_size = (250, 250)
img.thumbnail(output_size)
img.save(self.cover_image.path)
尝试使用您想要的尺寸而不是 250
推荐阅读
- android - 我可以在当前的 android 版本上获取当前的应用程序吗?
- java - 如何在 Java 中一次获取所有编译时错误?
- angular - 未在 Angular 中正确获取用户当前位置
- java - Apache Beam:如何在使用重复数据删除功能时解决“ParDo 需要确定性密钥编码器才能使用状态和计时器”
- three.js - Three.js:将模板剪辑与 EffectComposer 结合起来遇到问题
- javascript - EJS 中的数组在 NodeJS 中返回未定义和空值 - Express
- javascript - 当骰子的结果是 20 和 1 时,如何让机器人说出不同的响应?
- swift - 使用 Accelerate 框架执行规范化
- python - 用python创建一对用户ID
- python - TypeError:float() 参数必须是字符串或数字,而不是 'ImmutableMultiDict'