Reputation: 381
I stored an image to StringIO from PIL. When I store it to a file from stringIO, it doesn't produce the original image.
Code:
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 is below
Output image is below
What is wrong with the above code
Upvotes: 1
Views: 303
Reputation: 240
You need to use BytesIO and not StringIO. Also the destination file has to be opened in binary mode using "wb"
Here is code that works (cStringIO is replaced with 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())
Upvotes: 2