Search code examples
pythonpython-imaging-librarystringio

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


Solution

  • 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())