python实现将文字写到图片上,保存并显示新图片
时间: 2024-10-02 20:00:48 浏览: 117
在Python中,你可以使用一些库如`PIL`(Python Imaging Library)或者更现代的`Pillow`、`ImageDraw`和`matplotlib`等来实现文字写入图片的功能。这里是一个基本的例子,我们将使用`PIL`:
```python
from PIL import Image, ImageDraw, ImageFont
# 创建一个空白的图片
img_width, img_height = 400, 200
image = Image.new('RGB', (img_width, img_height), color='white')
draw = ImageDraw.Draw(image)
# 设置字体和文本
font_path = 'arial.ttf' # 字体文件路径
font_size = 50
text = "Hello, World!"
# 加载字体
try:
font = ImageFont.truetype(font_path, font_size)
except IOError:
print("无法加载字体文件,请检查路径或替换为可用字体")
# 定义位置和颜色
text_position = (50, 75)
text_color = 'black'
# 写入文字
draw.text(text_position, text, fill=text_color, font=font)
# 保存图片
image.save('output_image.png')
# 显示图片
image.show()
阅读全文
相关推荐

















