简体   繁体   English

使用 Pillow 在图像上传 Django 2 上调整大小并创建缩略图

[英]Resize and Create Thumbnail on Image Upload Django 2 using Pillow

I am trying to resize an image on upload and also create a thumbnail out of the same resized image.我正在尝试在上传时调整图像大小,并使用相同大小的图像创建缩略图。 I previously was able to resize the image without issues, however, when I tried adding in the thumbnail feature I was unable to get it working.我以前能够毫无问题地调整图像大小,但是,当我尝试添加缩略图功能时,我无法让它工作。 I have looked at all the other related questions and all of them are either outdated or haven't worked in my case.我查看了所有其他相关问题,所有这些问题要么已经过时,要么在我的情况下没有用。

models.py模型.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)

Originally I was using the resizeUploadedImage and createThumbnail methods and was successful with the resizing however the thumbnail was always empty on my admin page and db.最初我使用 resizeUploadedImage 和 createThumbnail 方法并成功调整大小,但缩略图在我的管理页面和数据库上始终为空。 Before I had 'editable=False' on the thumbnail as I wanted it to be created automatically behind the scenes.在缩略图上有“editable=False”之前,因为我希望它在幕后自动创建。 I thought that might be preventing the change so I took it out but it didn't change the results.我认为这可能会阻止更改,所以我将其取出,但它并没有改变结果。

Then I tried moving both into the save method (as I had previously run into issues when I moved my resize outside the save) but it still doesn't work properly.然后我尝试将两者都移到保存方法中(因为我之前在将调整大小移到保存之外时遇到了问题),但它仍然无法正常工作。

I see on several documents that it's best to put the super() call at the end of the save method, but when I do that I get我在几个文档中看到最好将 super() 调用放在 save 方法的末尾,但是当我这样做时,我得到了

 UNIQUE constraint failed: projects_project.id 

How can I create a thumbnail out of the cover_image and save it to the thumbnail field?如何从 cover_image 创建缩略图并将其保存到缩略图字段?

PS While running ./manage.py test projects it seems to be actually saving files to my disk which I thought wasn't supposed to happen so I assume its some kind of issue with my Pillow code. PS 在运行./manage.py test projects时,它似乎实际上是在将文件保存到我的磁盘上,我认为这是不应该发生的,所以我认为我的 Pillow 代码存在某种问题。 I end up with '1_cover.PNG', '1Project0_cover.PNG', '1Project1_cover.PNG', '2_cover.PNG' etc, etc, etc counting up to 9 even though my setuptestdata only has 'Project 1'.我最终得到 '1_cover.PNG'、'1Project0_cover.PNG'、'1Project1_cover.PNG'、'2_cover.PNG' 等,等等,即使我的 setuptestdata 只有“项目 1”,也计数到 9。

PPS I read somewhere that it's better to use Pillow's thumbnail function for resizing as it'll keep the aspect ratio whereas resize won't. PPS 我在某处读到,最好使用 Pillow 的缩略图 function 来调整大小,因为它会保持纵横比,而调整大小不会。 Does anyone have any insight on this?有人对此有任何见解吗?

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)

try this way with the size you wanted instead of 250尝试使用您想要的尺寸而不是 250

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM