Python中font使用方法
时间: 2024-02-13 14:04:02 浏览: 70
在Python中使用font,需要使用第三方库Pillow。以下是使用方法:
1. 安装Pillow库
在命令行中输入以下命令进行安装:
```
pip install Pillow
```
2. 导入Pillow库
在代码中导入Pillow库:
```
from PIL import ImageFont
```
3. 创建字体对象
创建字体对象需要指定字体文件路径和字体大小。例如:
```
font = ImageFont.truetype('arial.ttf', 36)
```
其中,'arial.ttf'是字体文件路径,36是字体大小。
4. 在图像上添加文字
使用Pillow库中的ImageDraw模块,在图像上添加文字。例如:
```
from PIL import Image, ImageDraw, ImageFont
# 打开图像
image = Image.open('example.jpg')
# 创建字体对象
font = ImageFont.truetype('arial.ttf', 36)
# 在图像上添加文字
draw = ImageDraw.Draw(image)
draw.text((10, 10), 'Hello, world!', font=font, fill=(255, 255, 255))
# 保存图像
image.save('result.jpg')
```
其中,(10, 10)是文字左上角坐标,'Hello, world!'是要添加的文字,fill指定文字颜色,这里是白色。最后保存图像即可。
阅读全文
相关推荐
















