繁体   English   中英

在标头损坏的Python(PIL)中读取JPEG

[英]Reading a JPEG in Python (PIL) with broken header

我正在尝试在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文件中的JpegImageFile._open方法引发了SyntaxError异常,这是由于JPEG文件头中0xFFDA标记之前有几个多余的0x00字节0xFFDA

Corrupt JPEG data: 5 extraneous bytes before marker 0xda

就是说,尽管我尝试过的其他程序只是在标头末尾忽略了未知的0x00标记,但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不喜欢标头中的损坏数据,并且会因为发现而掉落。

我已向Pillow(友好的PIL叉子)提出了拉动请求,该请求应解决此问题。

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

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

暂无
暂无

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

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