3

我正在使用 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

然后我使用此方法在我的主视图方法中获取 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)

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

痕迹:

异常类型:/myapp/editAvatar 处的 AttributeError 异常值:读取

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

尼库尼

4

2 回答 2

4

以下是如何获取一个类文件对象,将其作为 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

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

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
于 2012-06-05T14:30:02.670 回答
1

您最好保存上传的图像,然后根据需要在模板中显示和调整大小。这样您就可以在运行时调整图像大小。sorl-thumbnail是 djano 应用程序,您可以使用它来调整模板图像大小,它易于使用,您也可以在视图中使用它。以下是此应用程序的示例

于 2012-06-05T11:27:07.560 回答