在日常工作中,我们常常需要制作一些带有文字说明的图片。如果想用Python的Pillow库给图片添加中文文字,并且希望文字能居中显示,可以按照以下步骤操作!🌟
首先,确保安装了Pillow库和适合的中文字体文件(如“msyh.ttc”)。接着,通过代码加载图片并设置文字样式:
```python
from PIL import Image, ImageDraw, ImageFont
打开图片
img = Image.open("example.jpg")
draw = ImageDraw.Draw(img)
设置字体与大小
font_path = "msyh.ttc"
font_size = 50
font = ImageFont.truetype(font_path, font_size)
获取图片尺寸
width, height = img.size
文本内容及位置计算(居中)
text = "你好,Pillow!"
text_width, text_height = draw.textsize(text, font)
position = ((width - text_width) / 2, (height - text_height) / 2)
添加文字到图片
draw.text(position, text, fill=(255, 255, 255), font=font)
保存结果
img.save("output.jpg")
```
运行后,你就能得到一张带有居中文本的新图片啦!📸💖
这种方法不仅适用于中文,还可以扩展到其他语言或特殊符号哦~快来试试吧!🚀