python中PIL报错:image file is truncated(图像文件被截断)

已解决,今天碰到这个问题,感谢scool_winter的博文

自己简单记录一下:

报错原因:图像文件是损坏的,所以无法读取。
解决办法:
1、找到损坏的图片,并删除
打印当前的图片名
print(imgname)
如下图,这个被损坏的图片,把它从文件夹中删除,程序就能正常运行。
在这里插入图片描述

2、在程序开头加上如下代码

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
探究原因

查看错误发生的代码处,代码文件是 ImageFile.py ,位于python的site-package文件夹内,下面是报错部分代码


try:
  # FIXME: This is a hack to handle TIFF's JpegTables tag.
  prefix = self.tile_prefix
except AttributeError:
  prefix = b""

for decoder_name, extents, offset, args in self.tile:
  decoder = Image._getdecoder(self.mode, decoder_name,
                              args, self.decoderconfig)
  seek(offset)
  decoder.setimage(self.im, extents)
  if decoder.pulls_fd:
      decoder.setfd(self.fp)
      status, err_code = decoder.decode(b"")
  else:
      b = prefix
      while True:
          try:
              s = read(self.decodermaxblock)
          except (IndexError, struct.error):  # truncated png/gif
              if LOAD_TRUNCATED_IMAGES:
                  break
              else:
                  raise IOError("image file is truncated")

          if not s:  # truncated jpeg
              self.tile = []

              # JpegDecode needs to clean things up here either way
              # If we don't destroy the decompressor,
              # we have a memory leak.
              decoder.cleanup()

              if LOAD_TRUNCATED_IMAGES:
                  break
              else:
                  raise IOError("image file is truncated "
                                "(%d bytes not processed)" % len(b))
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值