本文主要是介绍解决批量图像处理过程中:OSError: image file is truncated,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1:问题描述:
在进行图像处理过程中,批量读取图像进行处理的时候,遇到中间某个图像损坏,导致处理无法进行下去。并伴随着OSError: image file is truncated的异常。
字面自已,图像被截断,损坏,无法完成正常的读取。
2:问题分析
错误发生的代码位于python的site-package文件夹内,代码文件为 ImageFile.py 。具体代码:
import io
import struct
import sys
import warningsfrom . import Image
from ._util import isPathMAXBLOCK = 65536SAFEBLOCK = 1024 * 1024LOAD_TRUNCATED_IMAGES = False
"""Whether or not to load truncated image files. User code may change this."""ERRORS = {-1: "image buffer overrun error",-2: "decoding error",-3: "unknown error",-8: "bad configuration",-9: "out of memory error",
}
"""Dict of known error codes returned from :meth:`.PyDecoder.decode`.""" try:# FIXME: This is a hack to handle TIFF's JpegTables tag.prefix = self.tile_prefixexcept AttributeError:prefix = b""for decoder_name, extents, offset, args in self.tile:decoder = Image._getdecoder(self.mode, decoder_name, args, self.decoderconfig)try:seek(offset)decoder.setimage(self.im, extents)if decoder.pulls_fd:decoder.setfd(self.fp)status, err_code = decoder.decode(b"")else:b = prefixwhile True:try:s = read(self.decodermaxblock)except (IndexError, struct.error) as e:# truncated png/gifif LOAD_TRUNCATED_IMAGES:breakelse:raise OSError("image file is truncated") from eif not s: # truncated jpegif LOAD_TRUNCATED_IMAGES:breakelse:raise OSError("image file is truncated "f"({len(b)} bytes not processed)")
从上述代码可以看出,
LOAD_TRUNCATED_IMAGES = False,此时如果读取的图像损坏,则会执行如下代码:
while True:try:s = read(self.decodermaxblock)except (IndexError, struct.error) as e:# truncated png/gifif LOAD_TRUNCATED_IMAGES:breakelse:raise OSError("image file is truncated") from eif not s: # truncated jpegif LOAD_TRUNCATED_IMAGES:breakelse:raise OSError("image file is truncated "f"({len(b)} bytes not processed)")
从这段代码可以看出,只要LOAD_TRUNCATED_IMAGES为False,则总会抛出OSError: image file is truncated的异常。这就是无法跳过损坏图片进行继续处理的原因。
3:解决办法:
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
如果想要跳过损坏图像进行接下来的图像操作,则需要将LOAD_TRUNCATED_IMAGES的值置为True。具体操作在代码开头添加如上两行代码。
这篇关于解决批量图像处理过程中:OSError: image file is truncated的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!