首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >创建从django模型中的另一个ImageField派生的django ImageField

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

Stack Overflow用户
提问于 2018-08-11 14:24:45
回答 1查看 332关注 0票数 1

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

代码语言:javascript
运行
复制
original_pic = models.ImageField()

另外,我想存储一个图像,它将包含与original_pic相同的图片(图像),在另一个ImageField中存储水印。

代码语言:javascript
运行
复制
watermark_pic = models.ImageField(default=watermarkImage())

总之,我只想在original_pic上应用算法,并使用django模型将结果保存在watermark_pic中。

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

代码语言:javascript
运行
复制
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)

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-12 09:01:44

我不知道你的水印逻辑是什么样子。您可以通过重写save()方法来做到这一点。无论如何,我为您制作了一个简单的图像旋转示例。

代码语言:javascript
运行
复制
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设置任何值

更新

代码语言:javascript
运行
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51800593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档