【问题标题】:In Memory Image to Zipfile在内存中图像到 Zipfile
【发布时间】:2014-02-12 16:51:59
【问题描述】:

我写了这段代码:

with Image.open(objective.picture.read()) as image:
    image_file = BytesIO()
    exifdata = image.info['exif']
    image.save(image_file, 'JPEG', quality=50, exif=exifdata)
    zf.writestr(zipped_filename, image_file)

这应该打开存储在我的模型中的图像(这是在 Django 应用程序中)。我想在将图像文件添加到 zipfile (zf) 之前降低图像文件的质量。所以我决定使用 BytesIO 来防止在磁盘上写入无用的文件。虽然我在这里遇到错误。它说:
embedded NUL character
有人可以帮我解决这个问题吗?我不明白发生了什么。

【问题讨论】:

  • 该错误发生在哪里?你能提供完整的回溯吗?
  • 另外,不确定您是否需要BytesIO 对象...image 对象有一个.tobytes() 方法...
  • 我不明白。我应该如何在不创建新图像的情况下修改图像?这一切都是在我执行保存功能时发生的,尽管我真的不知道它应该如何工作。
  • 我很确定您特别需要pass in a bytestring to writestr。这意味着您应该按照 Jon 的建议去做,或者您应该使用 image_file.read()

标签: python django python-3.x pillow bytesio


【解决方案1】:

嗯,我有点笨。 Objective.picture.read() 返回一个字节字符串(真的很长的字节字符串......)所以我不应该使用 ImageImageFile.Parser() 并将该字节字符串提供给解析器,以便它可以返回一个图像,我可以一起工作。这是代码:

from PIL import ImageFile
from io import BytesIO

p = ImageFile.Parser()
p.feed(objective.picture.read())
image = p.close()
image_file = BytesIO()
exifdata = image.info['exif']
image.save(image_file, 'JPEG', quality=50, exif=exifdata)
# Here zf is a zipfile writer
zf.writestr(zipped_filename, image_file.getvalue())

close() 实际上返回的是从字节串中解析出来的图像。
这是文档:The ImageFile Documentation

【讨论】:

  • 如果你只点击链接,这里有一个完整的导入示例。虽然你是对的,但我现在正在添加这些内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
相关资源
最近更新 更多