我使用Django ImageKit来处理/裁剪上传的照片。我添加了自己的自定义处理器来为照片添加文本(如水印):
# ./example/processors.py
from django.conf import settings
from PIL import Image, ImageDraw, ImageFont
_default_font = ImageFont.truetype(settings.TEXT_OVERLAY_FONT_REGULAR, 24)
def add_text_overlay(image, text, font=_default_font):
rgba_image = image.convert('RGBA')
text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
image_draw = ImageDraw.Draw(text_overlay)
text_size_x, text_size_y = image_draw.textsize(text, font=font)
text_xy = ((rgba_image.size[0] / 2) - (text_size_x / 2), (rgba_image.size[1] / 2) - (text_size_y / 2))
image_draw.text(text_xy, text, font=font, fill=(255, 255, 255, 255))
image_with_text_overlay = Image.alpha_composite(rgba_image, text_overlay)
return image_with_text_overlay
class TextOverlayProcessor(object):
def __init__(self, text='Lorem ipsum dolor sit amet'):
"""
:param text: The overlay text, string.
"""
self.text = text
def process(self, img):
return add_text_overlay(image=img, text=self.text)
但是如何将值从字段传输到模型内部的自定义 ImageKit 处理器?像这样的东西:
# ./example/models.py
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
from .processors import TextOverlayProcessor
class Example(models.Model):
description = models.CharField('Description', ...)
image = models.ImageField('Picture', default=None)
image_800x800 = ImageSpecField(
source='image',
processors=[
ResizeToFill(800, 800),
TextOverlayProcessor(text=self.description) # but `self` is wrong and raise error
],
format='JPEG',
options={'quality': 100}
)
...
我很乐意解释评论和/或用例。