2

我需要将用户上传的图片调整为 1000px 并添加水印。我还需要创建缩略图(没有水印)。

class Watermark(object):
    def process(self, img):
        draw = ImageDraw.Draw(img)
        draw.line((0, 0) + img.size, fill=128)
        draw.line((0, img.size[1], img.size[0], 0), fill=128)
        return img


class Photo(models.Model):
    image = ProcessedImageField(upload_to='photo',
                                processors=[
                                    ResizeToFit(1000, 1000, upscale=False),
                                    Watermark(),
                                ],
                                format='JPEG')
    thumbnail = ImageSpecField(source='image',
                               processors=[
                                   ResizeToFill(200, 200),
                               ],
                               format='JPEG')

问题是缩略图是从已经处理的图像中创建的。鉴于不应保存原始图像,如何从原始图像创建缩略图?

4

1 回答 1

2

我使用easy_thumbnails和信号解决了这个问题:

# settings.py
THUMBNAIL_ALIASES = {
    'gallery': {
        'small': {'size': (200, 200), 'crop': True},
    },
}
THUMBNAIL_PROCESSORS = easy_thumbnails_defaults.THUMBNAIL_PROCESSORS + (
    'gallery.models.watermark_processor',
)

# gallery/models.py
def watermark_processor(image, watermark=False, **kwargs):
    if watermark:
        draw = ImageDraw.Draw(image)
        draw.line((0, 0) + image.size, fill=128)
        draw.line((0, image.size[1], image.size[0], 0), fill=128)
    return image

class Photo(models.Model):
    image = ThumbnailerImageField(upload_to='photo',
                                  resize_source={
                                      'size': (1000, 1000),
                                      'watermark': True,
                                  })

@receiver(pre_save, sender=Photo)
def make_thumbnail(sender, instance, **kwargs):
    easy_thumbnails.files.generate_all_aliases(instance.image, False)

不幸的是,将这个信号技巧与 ImageKit(如instance.thumbnail.generate())一起使用会引发 I/O 错误。

于 2015-10-06T09:01:28.517 回答