3

我一直在使用 sorl-thumbnail 一段时间没有问题。但是,开始出现以下错误:encoder error -2 when writing image file

以下代码导致错误:

from sorl.thumbnail import get_thumbnail
photobooth_thumbnail = get_thumbnail(img_file,
    PHOTOBOOTH_THUMB_SIZE, crop='center', quality=99)

作为img_fileDjango 模型的 ImageField 以及何时PHOTOBOOTH_THUMB_SIZE“足够大”。当我使用PHOTOBOOTH_THUMB_SIZE = '670'时,一切正常,但是当我将其增加到 时PHOTOBOOTH_THUMB_SIZE = '1280',出现了上述错误。

鉴于低级别消息,我怀疑这是 PIL 中的错误,而不是 sorl-thumbnail 中的错误。我想要更大的缩略图,所以我会很感激这方面的任何帮助。提前致谢。

4

3 回答 3

1

我最终修补了pil_engine.py文件/lib/python2.7/site-packages/sorl/thumbnail/engines

--- pil_engine.py   2013-09-09 03:58:27.000000000 +0000
+++ pil_engine_new.py   2013-11-05 21:19:15.053034383 +0000
@@ -79,6 +79,7 @@
             image.save(buf, **params)
         except IOError:
             params.pop('optimize')
+            ImageFile.MAXBLOCK = image.size[0] * image.size[1]
             image.save(buf, **params)
         raw_data = buf.getvalue()
         buf.close()

这为我解决了这个问题。

于 2014-02-06T06:04:52.457 回答
0

我在根据图像大小修改缩略图质量的帮助下解决了这个问题。

def thumbnail_quality_calc(size, max_block=720*720):
    q_ratio = size / max_block
    # can also include the PHOTOBOOTH_THUMB_SIZE in the logic to calculate the q_ratio to improve the formula
    return math.floor(100 - q_ratio)

from sorl.thumbnail import get_thumbnail
img_quality = thumbnail_quality_calc(size=img_file.size)
photobooth_thumbnail = get_thumbnail(img_file,PHOTOBOOTH_THUMB_SIZE, crop='center', quality=img_quality)

# example
# size = 1024*1024
# quality will be 97
# This will help you to prevent encoder error

如果图像的尺寸太大并且您希望其缩略图被裁剪但具有高质量,则会导致错误,您可以增加 MAX 块大小或降低质量。上述解决方案使用第二种方法,无需更改基本包代码即可帮助您。

于 2019-07-16T14:15:48.643 回答
0

看起来这个错误只发生在某些设置上的某些图像上。因此,正如@Pablo Antonio 所指出的,如果您更改 image.save() 的至少一个参数。我可能会工作。我执行以下操作:

def img_save(img):
    quality = 80  # Default level we start from and decrease till 30
    need_retry = True
    while need_retry:
        try:
            img.save(self.dst_image_file, 'JPEG', quality=quality, optimize=True, progressive=True)
        except IOError as err:
            quality = quality - 1
            if quality <= 20:
                need_retry = False
        else:
            need_retry = False
于 2016-12-07T13:37:50.797 回答