Python 图片添加文字
使用场景: 一般在物联网的领域中,会有图片上报的场景,但是有时候需要在图片上展示相关信息,就可以使用python预处理,然后展示
直接上代码不废话
一、安装依赖Pillow
(venv) PS D:\software_project\python\demo> pip install pillow
Requirement already satisfied: pillow in d:\software_project\python\demo\venv\lib\site-packages (10.1.0)
[notice] A new release of pip available: 22.3.1 -> 23.3.2
[notice] To update, run: python.exe -m pip install --upgrade pip
(venv) PS D:\software_project\python\demo>
这里我已经装好了
二、实现代码
from PIL import Image, ImageDraw, ImageFont
# 打开图片
image = Image.open("example.png")
# 创建画布和字体
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 36)
# 添加文字
text = "Hello, world!"
draw.text((2, 3), text, font=font, fill=(255, 255, 255))## 这里的2,3是文字其实位置,图片的左上角的2,3的像素位置
# 保存图片
image.save("output.jpg")