TheGuardener
TheGuardener

Reputation: 381

Storing image from StringIO to a file creates a distorted image

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

Original Image

Output image is below

Original Image

What is wrong with the above code

Upvotes: 1

Views: 303

Answers (1)

Shakir Zareen
Shakir Zareen

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

Related Questions