Pillow: Truncated progressive JPEGs do not load

Created on 8 Sep 2017  路  4Comments  路  Source: python-pillow/Pillow

What did you do?

I tried to open a truncated progressive JPEG image.

from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
im = Image.open('flower_prog_trunc.jpg')
im.show()

What did you expect to happen?

I expected to see the image with some quality loss due to truncation.

What actually happened?

Shown image was completely black.

What versions of Pillow and Python are you using?

Tested on Python 2.7.13, 3.4.7, 3.6.1, with Pillow 4.2.1 and 2.0.0.

Test image

flower_prog_trunc

Made from this image in Pillow tests:

convert -interlace plane flower.jpg - | dd of=flower_prog_trunc2.jpg bs=1024 count=30
Enhancement

Most helpful comment

There is a simple workaround for this issue. If you add 2 ending bytes of JPEG to the file (0xFF, 0xD9), it is correctly interpreted and no longer returns a black image. Example:

import io
from PIL import Image, ImageFile
with open('flower_prog_trunc.jpg', 'rb') as f:
    im = Image.open(io.BytesIO(f.read() + b'\xff\xd9'))
im.show()

All 4 comments

Yep. It does appear to do that. It doesn't appear that we're getting anything back from jpeg_start_decompress, but it's consuming the entire input, so the next time there's nothing left in the file and we return instead of throwing an error.

    case 2:
        /* Set things up for decompression (this processes the entire
           file if necessary to return data line by line) */
        if (!jpeg_start_decompress(&context->cinfo))        <------------
            break;

        state->state++;
        /* fall through */

There is a simple workaround for this issue. If you add 2 ending bytes of JPEG to the file (0xFF, 0xD9), it is correctly interpreted and no longer returns a black image. Example:

import io
from PIL import Image, ImageFile
with open('flower_prog_trunc.jpg', 'rb') as f:
    im = Image.open(io.BytesIO(f.read() + b'\xff\xd9'))
im.show()

@nomarek Close or keep open for enhancement? I assume this is a feature we don't yet support.

Was this page helpful?
0 / 5 - 0 ratings