title: Reading a JPEG in Python (PIL) with broken header
body: <p>I'm trying to open a jpeg file in Python 2.7,</p>
  
  <pre><code>from PIL import Image
  im = Image.open(filename)
  </code></pre>
  
  <p>Which didn't work for me,</p>
  
  <pre><code>&gt;&gt;&gt; im = Image.open(filename)
  Traceback (most recent call last):
    File "&lt;pyshell#810&gt;", line 1, in &lt;module&gt;
      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
  </code></pre>
  
  <p>though when trying out on external viewers, it opened fine. Digging in a bit, it turns out that the <code>JpegImageFile._open</code> method from <code>PIL</code>'s <code>JpegImagePlugin.py</code> file raises a <code>SyntaxError</code> exception due to several extraneous <code>0x00</code> bytes before the <code>0xFFDA</code> marker in the JPEG's file header,</p>
  
  <pre><code>Corrupt JPEG data: 5 extraneous bytes before marker 0xda
  </code></pre>
  
  <p>That is, while other programs I tried simply ignored the unknown <code>0x00</code> marker towards the end of the header, <code>PIL</code> prefered to raise an exception, not allowing me to open the image.</p>
  
  <p><strong>QUESTION</strong>: Apart from editing <code>PIL</code>'s code directly, is there any workaround for opening JPEGs with problematic headers?</p>
  
  <p>The relevant code from the <code>JpegImageFile</code> class which raises the exception appears below, for your convenience:</p>
  
  <pre><code>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")
  </code></pre>