>我正在创建一个 django 项目,其中我使用 ImageField 在数据库中存储了一张图片(图像(作为...
original_pic = models.ImageField()
另外,我想存储一个将包含相同图片的图像(图像( 与另一个图像字段中的水印original_pic
一样。
watermark_pic = models.ImageField(default=watermarkImage())
简而言之,我只想在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)
注意:我知道在图像上应用水印的算法。
我不确定你的水印逻辑是什么样的。您可以通过重写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)