【问题标题】:Resizing uploaded files in django using PIL使用 PIL 在 django 中调整上传文件的大小
【发布时间】:2012-06-09 03:15:00
【问题描述】:

我正在使用 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 异常值: 阅读

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

尼库尼

【问题讨论】:

  • PIL Image 对象不是文件。您需要首先使用某种编码(例如 PNG)将 save() 指向 StringIO 对象。将文件写入 StringIO 后不要忘记seek(0)!旁注:为什么不直接从buf 读取并避免额外的包装器StringIO?
  • 卡梅伦,感谢您的回复。我对此真的很陌生。而且我真的不明白发生了什么。我试图拼凑 sn-ps 以使其工作。如何保存到 StringIO 对象。最顶层方法中的 resizedImage.save().seek(0) 是否足够好?如果您可以向我展示一些示例代码或记录此内容的地方,那就太好了:) 谢谢。
  • 因为您似乎关心调整头像的大小,这是非常常见和标准的事情:而不是直接使用像 easy_thumbnails 这样的专用应用程序(也使用 PIL)使用 PIL 调整图像大小可能会有所作为对你来说更容易:easy-thumbnails.readthedocs.org/en/latest/usage/#python

标签: python django file-upload resize python-imaging-library


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    以下是获取类文件对象的方法,将其作为 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 2014-12-07
      • 2014-11-29
      • 2017-04-01
      • 1970-01-01
      • 2013-10-03
      • 2011-02-20
      相关资源
      最近更新 更多