我正在创建一个django项目,其中已使用ImageField作为数据库将图片存储在数据库中。
bundle install
rails g mongoid:config
此外,我想将包含与原始图片相同的图片(图像)和带有水印的图片存储在另一个ImageField中。
original_pic = models.ImageField()
简而言之,我只想在original_pic上应用算法,然后使用Django模型将结果保存在watermark_pic中
将水印应用于图像的算法(逻辑)如下...
display_pic = models.ImageField(null=True, blank=True)
我的Models.py包含以下照片模型,该照片模型将覆盖保存方法以将值存储在def watermark_image_with_text(filename):
text = 'PicMesh'
color = 'blue'
fontfamily = 'arial.ttf'
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_image = Image.alpha_composite(image, imageWatermark)
my_image.convert('RGB').save('D:\Github\PicMesh\media\water_'+
filename.name + '.png')
return 'D:\Github\PicMesh\media\water_'+filename.name + '.png'
中。
display_pic
代码存在的问题是,它可以完美处理所有格式的图像,例如png,jpg,jpeg等,但是无法处理tif格式的图像。
调用class Photo(models.Model):
format_of_tags = (
('PNG', 'PNG'),
('JPG', 'JPG'),
('JPEG', 'JPEG'),
('Exif', 'Exif'),
('TIF', 'TIF'),
('GIF', 'GIF'),
('WEBP', 'WEBP'),
('SVG', 'SVG'),
)
title = models.CharField(max_length=150)
format = models.CharField(max_length=20, choices=format_of_tags, blank=False)
tags = models.CharField(max_length=250)
original_pic = models.ImageField()
display_pic = models.ImageField(null=True, blank=True)
description = models.CharField(max_length=1000)
photographer = models.ForeignKey('Photographer', on_delete=models.CASCADE)
category = models.ForeignKey('Categories', on_delete=models.CASCADE, default=0)
# Overwrites save method and set value of display_pic by default
def save(self, *args, **kwargs):
if not self.pk:
rotate_img_name = watermark_image_with_text(self.original_pic)
self.display_pic = rotate_img_name
super().save(*args, **kwargs)
方法时出现OSError
错误引用如下...
save()