首页 文章

Python PIL:如何将PNG图像写入字符串

提问于
浏览
82

我使用PIL生成了一个图像 . 如何将其保存到内存中的字符串? Image.save() 方法需要一个文件 .

我想在字典中存储几个这样的图像 .

6 回答

  • 162

    随着现代(截至2017年中期的Python 3.5和Pillow 4.0):

    StringIO似乎不再像过去那样工作了 . BytesIO类是处理此问题的正确方法 . Pillow的save函数需要一个字符串作为第一个参数,并且令人惊讶地看不到StringIO . 以下类似于较旧的StringIO解决方案,但使用BytesIO .

    from io import BytesIO
    from PIL import Image
    
    image = Image.open("a_file.png")
    faux_file = BytesIO()
    image_data = faux_file.getvalue()
    image.save(faux_file, 'png')
    
  • 25

    您可以使用BytesIO类来获取行为类似于文件的字符串的包装器 . BytesIO 对象提供与文件相同的接口,但将内容保存在内存中:

    import io
    
    with io.BytesIO() as output:
        image.save(output)
        contents = output.getvalue()
    

    如果PIL尝试自动检测输出格式,这可能会导致 KeyError . 要避免此问题,您可以手动指定格式:

    image.save(output, format="GIF")
    

    在引入 io 模块之前的旧Python 2版本中,您将使用StringIO模块 .

  • 12

    对于Python3,需要使用BytesIO:

    from io import BytesIO
    from PIL import Image, ImageDraw
    
    image = Image.new("RGB", (300, 50))
    draw = ImageDraw.Draw(image)
    draw.text((0, 0), "This text is drawn on image")
    
    byte_io = BytesIO()
    
    image.save(byte_io, 'PNG')
    

    阅读更多:http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image

  • 23

    某事情对我有用
    因为......

    Imaging / PIL / Image.pyc第1423行 - >引发KeyError(ext)#未知扩展名

    它试图从文件名中的扩展名检测格式,这在StringIO案例中是不存在的

    您可以通过在参数中自己设置格式来绕过格式检测

    import StringIO
    output = StringIO.StringIO()
    format = 'PNG' # or 'JPEG' or whatever you want
    image.save(output, format)
    contents = output.getvalue()
    output.close()
    
  • 8

    save()可以采用类似文件的对象和路径,因此您可以像StringIO一样使用内存缓冲区:

    buf= StringIO.StringIO()
    im.save(buf, format= 'JPEG')
    jpeg= buf.getvalue()
    
  • 6

    当你说“我想将这些图像的数量存储在字典中”时,目前尚不清楚这是否是内存中的结构 .

    您无需执行任何操作即可在内存中粘贴图像 . 只需将 image 对象保留在字典中即可 .

    如果您要将字典写入文件,可能需要查看 im.tostring() 方法和 Image.fromstring() 函数

    http://effbot.org/imagingbook/image.htm

    im.tostring()=> string使用标准的“原始”编码器返回包含像素数据的字符串 . Image.fromstring(mode,size,data)=> image使用标准的“原始”解码器从字符串中的像素数据创建图像内存 .

    当您交换文件时,“格式”(.jpeg,.png等)仅在磁盘上很重要 . 如果您不交换文件,格式无关紧要 .

相关问题