gpt4 book ai didi

python - 在 Python (PIL) 中读取带有损坏 header 的 JPEG

转载 作者:行者123 更新时间:2023-12-04 19:06:50 24 4
gpt4 key购买 nike

我正在尝试在 Python 2.7 中打开一个 jpeg 文件,

from PIL import Image
im = Image.open(filename)

这对我不起作用,
>>> im = Image.open(filename)
Traceback (most recent call last):
File "<pyshell#810>", line 1, in <module>
im = Image.open(filename)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1980, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file

尽管在外部查看器上试用时,它打开得很好。深入挖掘了一下,原来是 JpegImageFile._open方法来自 PILJpegImagePlugin.py文件引发 SyntaxError由于几个无关的异常(exception) 0x00 0xFFDA 之前的字节JPEG 文件头中的标记,
Corrupt JPEG data: 5 extraneous bytes before marker 0xda

也就是说,虽然我尝试过的其他程序只是忽略了未知的 0x00 header 末尾的标记, PIL更喜欢引发异常,不允许我打开图像。

问题 : 除了编辑 PIL的代码,是否有任何解决方法可以打开带有问题标题的 JPEG?

相关代码来自 JpegImageFile为方便起见,下面显示了引发异常的类:
def _open(self):

s = self.fp.read(1)

if ord(s[0]) != 255:
raise SyntaxError("not a JPEG file")

# Create attributes
self.bits = self.layers = 0

# JPEG specifics (internal)
self.layer = []
self.huffman_dc = {}
self.huffman_ac = {}
self.quantization = {}
self.app = {} # compatibility
self.applist = []
self.icclist = []

while 1:

s = s + self.fp.read(1)

i = i16(s)

if MARKER.has_key(i):
name, description, handler = MARKER[i]
# print hex(i), name, description
if handler is not None:
handler(self, i)
if i == 0xFFDA: # start of scan
rawmode = self.mode
if self.mode == "CMYK":
rawmode = "CMYK;I" # assume adobe conventions
self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))]
# self.__offset = self.fp.tell()
break
s = self.fp.read(1)
elif i == 0 or i == 65535:
# padded marker or junk; move on
s = "\xff"
else:
raise SyntaxError("no marker found")

最佳答案

PIL 不喜欢 header 中的损坏数据,并且正如您所发现的那样失败。

我已经向 Pillow(友好的 PIL 分支)提出了一个拉取请求,应该可以解决这个问题。

它尚未被接受,但希望它会在几个月后发布 2.5.0 版。同时,您可以在这里试用:https://github.com/python-imaging/Pillow/pull/647

作为一种解决方法,您可以使用 ImageMagick 之类的东西首先将有问题的图像转换为 png 之类的图像,然后在 PIL/Pillow 中使用它们。

关于python - 在 Python (PIL) 中读取带有损坏 header 的 JPEG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22610684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com