55

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

Gil Hamilton
  • 11,973
  • 28
  • 51
ato
  • 854
  • 1
  • 6
  • 9
  • Why don't you read the image into numpy array? – Viktor Kerkez Aug 28 '13 at 15:06
  • 1
    @ViktorKerkez because I want to manipulate the Bytes of the images. I have working code for the Manipulation part, but now I want to verify the output image is actually not totally broken. So I _have_ to work with bytearrays – ato Aug 28 '13 at 15:13

1 Answers1

72

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)
Ahmed
  • 2,825
  • 1
  • 25
  • 39
Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85