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

标签 python python-imaging-library stringio

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

相关文章:

python - 在 Numpy 中获取向量集并集的有效方法

python - 与 for 循环一起使用的 String join() 方法

Python:如何通过用户定义的函数拟合曲线?

python - 如何在 python 中逐像素生成图像?

python-3.x - tempfile 模块和 IO 类文件对象有什么区别

python - 使用 matplotlib 添加额外的轴刻度

python - 使用 Python 图像库创建非常大的图像

python - 将 PIL 图像转换为字节,出现错误

python - 使用 read_csv 转换 StringIO 时使用 Pandas 的奇怪输出

python - 内存 Zip 文件中的 Python 错误