繁体   English   中英

为什么会出现 IndexError:字符串索引超出范围?

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

我在 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')

本质上,我正在使用一个 .bin 文件,该文件包含多个图像文件的十六进制代码
像 123451234512345... 聚集在一起然后保存。 问题是我收到以下错误:

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

我找到了 PngImagePlugin.py 并查看了它的内容:

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)

我会尝试修补,但我担心我会搞砸 png 和 PIL,这对开始工作来说很麻烦。

谢谢

在这个阶段似乎len(s) < 4

len = i32(s)

意思就是

s = self.fp.read(8)

没有读取整个 4 个字节

您传递的 fp 中的数据可能对图像解码器没有意义。

仔细检查您是否正确切片

确保您传入的字符串的长度至少为 4。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM