from PIL import Image, ImageDraw, ImageFont
background_image = Image.open(background_image)
background_image = background_image.convert('RGBA')最近自然在画图啦!先打开一个背景图,备注一下Image.open()打开的是图片文件,所以如果是文件路径要记得转化哦!教你们一个小技巧,打开网络图片(运行时记得换张图片,怕吓到你们)
response = req.get("https://cdn.pixabay.com/photo/2020/04/03/07/26/eye-4997724__340.png")
image = Image.open(BytesIO(response.content))简单的添加一个图标:
# 图标 x y x+w x+h
icon_box = (96, 99, 96 + 90, 99 + 42)
icon_region = poster_icon_url.resize((icon_box[2] - icon_box[0], icon_box[3] - icon_box[1]))
background_image.paste(icon_region, icon_box)
前面一大堆跟我们的标题都没有关系,接下来重点:
from PIL import Image, ImageDraw, ImageFont
import textwrap
# 添加一个标题
# 设置需要显示的字体
# 第三方库存在该字体的写法如下:
# fontpath = "font/msyh.ttc"
# 项目中存在该字体的写法如下: zby/config/msyh.ttc这个是我的项目结构然后在config加了字体
# fontpath = r"../config/msyh.ttc"
# 解决Linux上报错OSError: cannot open resource的写法:
fontpath = "/usr/share/fonts/MSYH.TTC"
font = ImageFont.truetype(fontpath, 44)
draw = ImageDraw.Draw(background_image)
# 绘制标题 width=20 20个字的大小
item_title = textwrap.wrap(item_title, width=20)
draw.text((210, 90), item_title[0], font=font, fill=(51, 51, 51))
# 换行
draw.text((90, 165), item_title[1], font=font, fill=(51, 51, 51))中间有一个 :fontpath = "/usr/share/fonts/MSYH.TTC",解释解释:
Linux
查看字体
fc-list
安装
yum -y install fontconfig
安装成功后会看到/usr/share/fonts 的目录
cd /usr/share/fonts 进入目录后添加需要的字体
重启
fc-cache -fv
画图结尾一下
from io import BytesIO
# 单元测试时会弹出你生成的海报
background_image.show()
a = BytesIO()
background_image.save(a, 'png')
a.seek(0)
return a
版权声明:本文为ZBYTSL原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。