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

Go To StackoverFlow.com


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)
pngimage1 = Image.open(slicedFile2)
gifimage1 = Image.open(slicedFile3)
pngimage2 = Image.open(slicedFile4)

in essence i'm taking a .bin file that has hex code for several image files jumbled
like 123451234512345... and clumping together then saving. The problem is i'm 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 the PngImagePlugin.py and I looked at 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]
        s = self.fp.read(8)
        cid = s[4:]
        pos = self.fp.tell()
        len = i32(s) (lines 88-96)

i would try tinkering, but I'm afraid I'll screw up png and PIL, which have been erksome to get working.


2012-04-04 05:31
by cah
The error isn't with PIL, it is with your slicing. Confirm that you are slicing correctly - Burhan Khalid 2012-04-04 05:40
Is there supposed to be 4 files or 5 - John La Rooy 2012-04-04 05:45


It would appear that len(s) < 4 at this stage

len = i32(s)

Which means that

s = self.fp.read(8)

isn't reading the whole 4 bytes

probably the data in the fp you are passing isn't making sense to the image decoder.

Double check that you are slicing correctly

2012-04-04 05:39
by John La Rooy
So is there something specific I can do? Thanks - cah 2012-04-04 05:40
I'm sorry, I'm still not really sure what I should do to fix it - cah 2012-04-04 05:46


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

2012-04-04 05:41
by Marcin