【问题标题】:Storing image from StringIO to a file creates a distorted image将图像从 StringIO 存储到文件会创建扭曲的图像
【发布时间】:2020-04-07 13:39:02
【问题描述】:

我将图像从 PIL 存储到 StringIO。当我将它从 stringIO 存储到文件时,它不会生成原始图像。

代码:

    from PIL import Image
    from cStringIO import StringIO
    buff=StringIO()
    img = Image.open("test.jpg")
    img.save(buff,format='JPEG')
    #img=img.crop((1,1,100,100))
    buff.seek(0)
    #Produces a distorted image
    with open("vv.jpg", "w") as handle:
         handle.write(buff.read())

原图如下

输出图片如下

上面的代码有什么问题

【问题讨论】:

    标签: python python-imaging-library stringio


    【解决方案1】:

    您需要使用 BytesIO 而不是 StringIO。 还必须使用“wb”以二进制模式打开目标文件

    这是有效的代码(cStringIO 替换为 io)

    from PIL import Image
    from io import BytesIO
    buff=BytesIO()
    img = Image.open('test.jpg')
    img.save(buff,format='JPEG')
    #img=img.crop((1,1,100,100))
    buff.seek(0)
    #Produces a distorted image
    with open('vv.jpg', "wb") as handle:
         handle.write(buff.read())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2016-01-07
      • 2016-07-25
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      • 2014-08-13
      相关资源
      最近更新 更多