本文将通过一个具体的代码示例,展示如何使用Pillow在图像上添加或修改文本信息。
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
# Load the image
img_path = 'C:\\Users\\heish\\Downloads\\111a7dd0d5e04bfb9c07dc1f6e0686fa.png'
image = Image.open(img_path)
# Initialize drawing context with the image as background
draw = ImageDraw.Draw(image)
# Text settings
text = "99.999"
position = (580, 230) # position where the new text should be
text_color = (255, 255, 255)
font_size = 50
font_path = "C:\\Windows\\Fonts\\simsunb.ttf"
font = ImageFont.truetype(font_path, font_size)
# Overwrite the existing number with a rectangle that matches the background
rectangle_position = (position[0], position[1], position[0] + 210, position[1] + 60)
draw.rectangle(rectangle_position, fill=(18, 18, 18))
# Draw the new text onto the image
draw.text(position, text, fill=text_color, font=font)
# Save the edited