Search code examples
djangoimagejpegsorl-thumbnail

sorl-thumbnail: Preserve "progressiveness" of JPEG files


Most of all JPEG files uploaded to my sites are saved in progressive format, but no thumbnail generated by sorl-thumbnail is generated as progressive when the original image is. This is essential when creating thumbnails of large images, for instance, for display within a carousel/slider.

I have sumbitted an issue on sorl's tracker, but I think maybe creating a custom backend based on the existing ones, could solve the issue. Any ideas?

Thanks!


Solution

  • from sorl.thumbnail.engines import pil_engine
    
    class ProgressiveBackend(pil_engine.Engine):
        def _get_raw_data(self, image, format_, quality):
            ImageFile.MAXBLOCK = 1024 * 1024
            buf = StringIO()
            try:
                if format_=='JPEG':
                    image.save(buf, format=format_, quality=quality, optimize=1, progressive=image.progressive)
                else:
                    image.save(buf, format=format_, quality=quality, optimize=1)
            except IOError:
                image.save(buf, format=format_, quality=quality)
            raw_data = buf.getvalue()
            buf.close()
            return raw_data