创建从django模型中的另一个ImageField派生的django ImageField

时间:2018-08-11 14:24:46

标签: python django image django-models watermark

我正在创建一个django项目,其中已使用ImageField作为数据库将图片存储在数据库中。

original_pic = models.ImageField()

我还想存储一个包含相同图片的图像(图像) 与original_pic一样,在另一个ImageField中带有水印。

watermark_pic = models.ImageField(default=watermarkImage())

简而言之,我只想在d original_pic上应用算法并使用Django模型将结果保存在watermark_pic

将水印应用于图像的算法(逻辑)如下...

def watermarkImage(filename, text, color, fontfamily):
    image = Image.open(filename).convert('RGBA')
    imageWatermark = Image.new('RGBA', image.size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(imageWatermark)
    width, height = image.size
    font = ImageFont.truetype(fontfamily, int(height / 20))
    textWidth, textHeight = draw.textsize(text, font)
    x = width / 5
    y = height / 6
    draw.text((x, y), text, color, font)
    return Image.alpha_composite(image, imageWatermark)

注意:我知道在图像上应用水印的算法。

1 个答案:

答案 0 :(得分:1)

我不确定您对水印逻辑的外观如何。您可以通过覆盖 save() 方法来实现。无论如何,我为您制作了一个简单的图像旋转示例。


from PIL import Image


def rotate_image(image_fp):
    im = Image.open(image_fp)
    rotate = im.rotate(45)
    filename = "rotated_" + image_fp.name
    rotate.save(filename)
    return filename


class MyBaseImageModel(models.Model):
    # your model
    original_pic = models.ImageField()
    watermark_pic = models.ImageField(null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.pk:
            rotate_img_name = rotate_image(self.original_pic)
            self.watermark_pic = rotate_img_name
        super().save(*args, **kwargs)

创建图像时,您不想为watermark_pic放置任何值

更新

def watermarkImage(filename, text, color, fontfamily):
    image = Image.open(filename).convert('RGBA')
    imageWatermark = Image.new('RGBA', image.size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(imageWatermark)
    width, height = image.size
    font = ImageFont.truetype(fontfamily, int(height / 20))
    textWidth, textHeight = draw.textsize(text, font)
    x = width / 5
    y = height / 6
    draw.text((x, y), text, color, font)
    my_img = Image.alpha_composite(image, imageWatermark)
    my_img.save('water_'+filename.name)
    return 'water_'+filename.name

class MyBaseImageModel(models.Model):
    # your model
    original_pic = models.ImageField()
    watermark_pic = models.ImageField(null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.pk:
            rotate_img_name = watermarkImage(your args)
            self.watermark_pic = rotate_img_name
        super().save(*args, **kwargs)