Django ImageKit:添加水印并创建缩略图

时间:2015-10-05 04:49:41

标签: python django django-imagekit

我需要将用户上传的图像放到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')

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

1 个答案:

答案 0 :(得分:0)

I solved the problem using easy_thumbnails and signals:

# 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)

Unfortunately usage this signal trick with ImageKit (like instance.thumbnail.generate()) raises I/O error.