PIL: Convert Bytearray to Image

ato picture ato · Aug 28, 2013 · Viewed 63.7k times · Source

I am trying to verify a bytearray with Image.open and Image.verify() without writing it to disk first and then open it with im = Image.open(). I looked at the .readfrombuffer() and .readfromstring() method, but there I need the size of the image (which I could only get when converting the bytestream to an image).

My Read-Function looks like this:

def readimage(path):
    bytes = bytearray()
    count = os.stat(path).st_size / 2
    with open(path, "rb") as f:
        print "file opened"
        bytes = array('h')
        bytes.fromfile(f, count)
    return bytes

Then as a basic test I try to convert the bytearray to an image:

bytes = readimage(path+extension)
im = Image.open(StringIO(bytes))
im.save(savepath)

If someone knows what I am doing wrong or if there is a more elegant way to convert those bytes into an image that'd really help me.

P.S.: I thought I need the bytearray because I do manipulations on the bytes (glitch them images). This did work, but I wanted to do it without writing it to disk and then opening the imagefile from the disk again to check if it is broken or not.

Edit: All it gives me is a IOError: cannot identify image file

Answer

Viktor Kerkez picture Viktor Kerkez · Aug 28, 2013

If you manipulate with bytearrays, then you have to use io.BytesIO. Also you can read a file directly to a bytearray.

import os
import io
import PIL.Image as Image

from array import array

def readimage(path):
    count = os.stat(path).st_size / 2
    with open(path, "rb") as f:
        return bytearray(f.read())

bytes = readimage(path+extension)
image = Image.open(io.BytesIO(bytes))
image.save(savepath)