gpt4 book ai didi

python - 将图像从 StringIO 存储到文件会创建扭曲的图像

转载 作者:行者123 更新时间:2023-12-01 00:15:58 24 4
gpt4 key购买 nike

我将图像从 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())

原图如下

Original Image

输出图像如下

Original Image

上面的代码有什么问题

最佳答案

您需要使用 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())

关于python - 将图像从 StringIO 存储到文件会创建扭曲的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59333791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com