gpt4 book ai didi

python - 使用 PIL 在 Django 中调整上传文件的大小

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:59 25 4
gpt4 key购买 nike

我正在使用 PIL 通过这种方法调整上传文件的大小:

def resize_uploaded_image(buf):
imagefile = StringIO.StringIO(buf.read())
imageImage = Image.open(imagefile)

(width, height) = imageImage.size
(width, height) = scale_dimensions(width, height, longest_side=240)

resizedImage = imageImage.resize((width, height))
return resizedImage

然后我使用此方法在我的主视图方法中获取调整大小的图像:

image = request.FILES['avatar']
resizedImage = resize_uploaded_image(image)
content = django.core.files.File(resizedImage)
acc = Account.objects.get(account=request.user)
acc.avatar.save(image.name, content)

但是,这给了我“读取”错误。

跟踪:

Exception Type: AttributeError at /myapp/editAvatar Exception Value: read

知道如何解决这个问题吗?我已经做了好几个小时了!谢谢!

尼昆杰

最佳答案

以下是获取类文件对象的方法,在 PIL 中将其作为图像进行操作,然后将其转回类文件对象:

def resize_uploaded_image(buf):
image = Image.open(buf)

(width, height) = image.size
(width, height) = scale_dimensions(width, height, longest_side=240)

resizedImage = image.resize((width, height))

# Turn back into file-like object
resizedImageFile = StringIO.StringIO()
resizedImage.save(resizedImageFile , 'PNG', optimize = True)
resizedImageFile.seek(0) # So that the next read starts at the beginning

return resizedImageFile

请注意,PIL 图像已经有一个方便的 thumbnail() 方法。这是我在自己的项目中使用的缩略图代码的变体:

def resize_uploaded_image(buf):
from cStringIO import StringIO
import Image

image = Image.open(buf)

maxSize = (240, 240)
resizedImage = image.thumbnail(maxSize, Image.ANTIALIAS)

# Turn back into file-like object
resizedImageFile = StringIO()
resizedImage.save(resizedImageFile , 'PNG', optimize = True)
resizedImageFile.seek(0) # So that the next read starts at the beginning

return resizedImageFile

关于python - 使用 PIL 在 Django 中调整上传文件的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10891626/

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