我正在使用 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
我是一名优秀的程序员,十分优秀!