如何用PIL调整上传文件的大小?

2024-05-16 04:12:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我意识到这是一个微不足道的任务,这个问题被回答了很多次,但我就是搞不懂。在将图像保存到磁盘之前,有没有办法调整和裁剪图像?我发现的所有解决方案都倾向于存储图像,调整大小,然后再次存储。我能做这个吗?在

# extending form's save() method
def save(self):
    import Image as pil

    # if avatar is uploaded, we need to scale it
    if self.files['avatar']:
        img = pil.open(self.files['avatar'])
        img.thumbnail((150, 150), pil.ANTIALIAS)

        # ???
        # self.files['avatar'] is InMemoryUpladedFile
        # how do I replace self.files['avatar'] with my new scaled image here?
        # ???

    super(UserForm, self).save()

Tags: 图像selfformimgifpilissave
2条回答

我能弄明白。您只需将修改后的文件另存为StringIO,然后从中创建一个新的InMemoryUploadedFile。以下是完整的解决方案:

def save(self):

    import Image as pil
    import StringIO, time, os.path
    from django.core.files.uploadedfile import InMemoryUploadedFile

    # if avatar is uploaded, we need to scale it
    if self.files['avatar']:
        # opening file as PIL instance
        img = pil.open(self.files['avatar'])

        # modifying it
        img.thumbnail((150, 150), pil.ANTIALIAS)

        # saving it to memory
        thumb_io = StringIO.StringIO()
        img.save(thumb_io,  self.files['avatar'].content_type.split('/')[-1].upper())

        # generating name for the new file
        new_file_name = str(self.instance.id) +'_avatar_' +\
                        str(int(time.time())) + \
                        os.path.splitext(self.instance.avatar.name)[1]

        # creating new InMemoryUploadedFile() based on the modified file
        file = InMemoryUploadedFile(thumb_io,
                                    u"avatar", # important to specify field name here
                                    new_file_name,
                                    self.files['avatar'].content_type,
                                    thumb_io.len,
                                    None)

        # and finally, replacing original InMemoryUploadedFile() with modified one
        self.instance.avatar = file

    # now, when form will be saved, it will use the modified file, instead of the original
    super(UserForm, self).save()

我不熟悉PIL,但正如我在docs中看到的,您可以将file对象作为“file”参数传递给“open”函数。在

Djangorequest.FILES存储上载的文件对象-上载文件的简单包装器(存储在内存中或临时文件中),它支持读取、查找和告诉操作,因此可以直接传递给PIL“open”函数。在

相关问题 更多 >