2

I need to fit user's uploaded image to 1000px and put a watermark. Also I need to create thumbnail (without watermark).

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

The trouble is that the thumbnail is created from the already processed image. How to create a thumbnail from the original image, given that the original image should not be saved?

Alexander
  • 41
  • 1
  • 6

1 Answers1

2

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.

Alexander
  • 41
  • 1
  • 6