将图像从 StringIO 存储到文件会产生扭曲的图像
Storing image from StringIO to a file creates a distorted image
我将图像从 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())
原图如下
输出图片如下
上面的代码有什么问题
您需要使用 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())
我将图像从 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())
原图如下
输出图片如下
上面的代码有什么问题
您需要使用 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())