IOError: 读取图像文件时数据流中断

3
这是一段代码(一个简单的Python代码,可以将数字添加到图片中):

from PIL import Image, ImageDraw, ImageFont

def addnum(number, filepath):
    img = Image.open(filepath)

    width, height = img.size

    draw = ImageDraw.Draw(img)

    front_size = height/4
    ttf_front = ImageFont.truetype('Arial.ttf', front_size)
    draw.text((width - front_size, 0), number, (255, 0, 0), font = ttf_front)

    del draw
    img.save('wechat_addnum.jpg')
    img.show()

if __name__ == '__main__':
    addnum('4','wechat.jpg')



Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/Users/JourneyWoo/Python/python100/python001/python000.py", line 27, in <module>
addnum('4','wechat.jpg')
File "/Users/JourneyWoo/Python/python100/python001/python000.py", line 16, in addnum
draw = ImageDraw.Draw(img)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageDraw.py", line 299, in Draw
return ImageDraw(im, mode)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageDraw.py", line 60, in __init__
im.load()
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageFile.py", line 244, in load
raise_ioerror(err_code)
File "/Users/JourneyWoo/anaconda/lib/python2.7/site-packages/PIL/ImageFile.py", line 59, in raise_ioerror
raise IOError(message + " when reading image file")
IOError: broken data stream when reading image file

我不知道真正的问题所在,从Google和StackOverflow的其他问题中也找不到能够解决这个问题的方法。 谢谢!


1
你能否编辑你的问题以展示完整的堆栈跟踪信息? - Jean-François Fabre
同意,我们需要回溯来告诉你更多信息。 - Dmitry Belaventsev
谢谢,我已经更新了Q。 - Tozz
你应该尝试使用另一张图片。我从我的库中选择了一张图片(png格式)并且它可以正常工作。此外:font_size = height//4 使用整数除法,否则代码在Python 3中可能无法移植。有时候字体大小不可用,会出现资源错误... - Jean-François Fabre
1个回答

1

这是一个已知的问题。尝试使用pip install Pillow --upgrade更新Pillow。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接