gpt4 book ai didi

python - 如何在保存前使用 PIL 调整上传文件的大小?

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:31 24 4
gpt4 key购买 nike

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

# 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()

最佳答案

我能够弄清楚这一点。您只需将修改后的文件保存为 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()

关于python - 如何在保存前使用 PIL 调整上传文件的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23168670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com