首页 > 解决方案 > 使用 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 的缩略图功能来调整大小,因为它会保持纵横比,而调整大小不会。有人对此有任何见解吗?

标签: pythondjangopython-imaging-library

解决方案


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


推荐阅读