Why am I getting IndexError: string index out of range?

I am running the following code on ubuntu 11.10, python 2.7.2+.

import urllib
import Image
import StringIO
source = '/home/cah/Downloads/evil2.gfx'
dataFile = open(source, 'rb').read()
slicedFile1 = StringIO.StringIO(dataFile[::5])
slicedFile2 = StringIO.StringIO(dataFile[1::5])
slicedFile3 = StringIO.StringIO(dataFile[2::5])
slicedFile4 = StringIO.StringIO(dataFile[3::5])
jpgimage1 = Image.open(slicedFile1)
jpgimage1.save('/home/cah/Documents/pychallenge12.1.jpg')
pngimage1 = Image.open(slicedFile2)
pngimage1.save('/home/cah/Documents/pychallenge12.2.png')
gifimage1 = Image.open(slicedFile3)
gifimage1.save('/home/cah/Documents/pychallenge12.3.gif')
pngimage2 = Image.open(slicedFile4)
pngimage2.save('/home/cah/Documents/pychallenge12.4.png')

      

Basically, I take a .bin file that has a hex code for multiple image files, jumbled
as 123451234512345 ... and put it together and then save. The problem is I am getting the following error:

File "/usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py", line 96, in read
len = i32(s)
File "/usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py", line 44, in i32
return ord(c[3]) + (ord(c[2])<<8) + (ord(c[1])<<16) + (ord(c[0])<<24)
IndexError: string index out of range

      

I found PngImagePlugin.py and I looked what it had:

def i32(c):

    return ord(c[3]) + (ord(c[2])<<8) + (ord(c[1])<<16) + (ord(c[0])<<24) (line 44)

"Fetch a new chunk. Returns header information."

    if self.queue:
        cid, pos, len = self.queue[-1]
        del self.queue[-1]
        self.fp.seek(pos)
    else:
        s = self.fp.read(8)
        cid = s[4:]
        pos = self.fp.tell()
        len = i32(s) (lines 88-96)

      

I would try messing around, but I'm afraid I messed up png and PIL, which were ercommerce to work.

thank

+3


source to share


2 answers


It would seem len(s) < 4

at this stage

len = i32(s)

      

It means that

s = self.fp.read(8)

      



does not read whole 4 bytes

Probably the data in the passing fp doesn't make sense to the picture decoder.

Double check for correct slicing

+3


source


Make sure the string you are passing in is at least 4 in length.



-1


source







All Articles