需求说明
最近在做一个项目,其中有个需求,简单的来说是这样的:
前端输入一个字符串,在后台数据库中查询数据,将查询到的结果和media中存在的一个图片模板结合生成一个新的图片。最后将结果返回给前端。
实现技术
- django
- PIL
坑
- 读取django目录下的图片文件
这个坑,把我给坑了一晚上,一开始我使用相对路径,绝对路径,都没办法读取到,而且在网页上可以显示,但是本地写的py脚本就实现不了。很凉凉。后来翻阅了大量的博客,发现了一个麻烦但能实现的方案:先使用requests获取图片,然后再操作,但是这样的话,图片的质量会有所下降,并且效率比较低。
from PIL import Image, ImageDraw, ImageFont from io import BytesIO import requests response = requests.get('http://127.0.0.1:8000/media/1.jpg') response = response.content BytesIOObj = BytesIO() BytesIOObj.write(response) image = Image.open(BytesIOObj)
两分钟后。。。。
我发现原来是如此滴简单。。。。
在setting中配置完media的路径后,然后在相应的文件中引入,拼成的路径可以访问,但是要注意""的转码问题。# setting.py MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR,"media")
from PIL import Image, ImageDraw, ImageFont from xibao.settings import MEDIA_ROOT img = MEDIA_ROOT + "\\1.jpg" image = Image.open(img)
关于图片处理的代码
name = unicode(name ,"utf-8")
college = unicode(college, "utf-8")
major = unicode(major, "utf-8")
img = MEDIA_ROOT + "\\1.jpg" # 已有图片
new_img = MEDIA_ROOT + "\\result\\" + identity + ".jpg" # 生成的图片
color = "#67625A" # 设置颜色
# 打开图片
image = Image.open(img)
draw = ImageDraw.Draw(image)
width, height = image.size
name_x = 32
name_y = 263
name_text_front = ImageFont.truetype(r"C:\Windows\Fonts\simhei.ttf", 21)
draw.text((name_x, name_y), u'%s' % name, color, name_text_front)
college_x = 99
college_y = 364
college_text_front = ImageFont.truetype(r"C:\Windows\Fonts\simhei.ttf", 17)
draw.text((college_x, college_y), u'%s' % college, color, college_text_front)
major_x = 99
major_y = 396
major_text_front = ImageFont.truetype(r"C:\Windows\Fonts\simhei.ttf", 17)
draw.text((major_x, major_y), u'%s' % major, color, major_text_front)
# 生成图片
image.save(new_img)
最后说下应用
让我想起了。。。比如关于用户自定义水印、生成海报。