【问题标题】:Saving in memory file object with pillow用枕头保存在内存文件对象中
【发布时间】:2014-04-28 18:01:11
【问题描述】:

在我的 django 项目中,我有一个 inmemoryuploadedfile,然后我用 Pillow 打开它,旋转它,然后将其保存回自身。然而,最后一步实际上不起作用。当我将其保存到文件时,正确(旋转)图像被保存。如何保存回文件对象而不是实际文件?

    image = request.FILES['file']
    img = Image.open(image)
    img = img.rotate(90)
    img.save("sample.jpeg", "jpeg") #this is correct
    img.save(image, "jpeg") #this does not change the actual in memory image

【问题讨论】:

    标签: python django python-2.7 python-imaging-library pillow


    【解决方案1】:

    您必须重置保存上传文件的底层 StreamIO 对象的流位置。否则Image.save() 只会追加到流的末尾。

    在尝试再次从内存中读取文件之前,您可能还需要重置流位置。

    image = request.FILES['file']
    img = Image.open(image)
    img = img.rotate(90)
    image.seek(0)
    img.save(image, "jpeg")
    image.seek(0)
    image.read()
    

    请注意,UploadedFileInMemoryUploadedFile 的基类)会跟踪文件大小,如果您要更改底层文件对象,依赖于 InMemoryUploadedFile.size 的代码可能会混淆。

    【讨论】:

    • 我可以重新设置长度吗?我所做的只是旋转图像,但枕头确实剥离了 exif 数据,因此文件必须变得更小。
    • 您应该能够通过将 image.size 设置为新值来更新文件大小。您甚至可以尝试使用此处的 _get_size_from_underlying_file() 方法:github.com/django/django/blob/master/django/core/files/…。像 image.size = image._get_size_from_underlying_file()
    猜你喜欢
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2016-02-21
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多