用Python和PIL美化图像:文本覆盖技术实战

138 阅读3分钟
实战:在图像上添加或修改文本

本文将通过一个具体的代码示例,展示如何使用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 image
edited_img_path = 'C:\\Users\\heish\\Downloads\\111a7dd0d5e04bfb9c07dc1f6e0686fa\_1.png'
image.save(edited_img_path)

# Display the edited image
plt.imshow(image)
plt.axis('off') # Hide axes
plt.show()

edited_img_path

以下是我们的步骤和技术要点:

  1. 加载图像:首先,我们需要加载要编辑的图像。Pillow库的Image.open方法可以方便地完成这一任务。
  2. 初始化绘图上下文:接下来,通过ImageDraw.Draw方法,我们可以在已加载的图像上初始化一个绘图上下文。这是后续绘制文本或其他形状的基础。
  3. 文本设置:在绘制文本前,我们需要设置文本内容、位置、颜色和字体。这里特别注意,字体的选择和大小设置对最终的视觉效果有很大影响。
  4. 背景处理:如果需要在原有文本或图像上覆盖新文本,首先使用矩形绘制功能,以图像背景色覆盖原有区域,为新文本的添加做好准备。
  5. 绘制文本:使用draw.text方法,根据前面的设置在图像上绘制新的文本信息。
  6. 保存编辑后的图像:通过image.save方法,将编辑后的图像保存到指定路径。
  7. 显示图像:最后,利用matplotlib.pyplot库,我们可以在Jupyter Notebook中直接显示编辑后的图像,方便立即查看效果。

111a7dd0d5e04bfb9c07dc1f6e0686fa_1.png

实用技巧和注意事项
  • 在选择字体和大小时,考虑文本在图像中的视觉效果和协调性。
  • 覆盖原有文本或图像元素时,确保使用与背景色匹配的颜色,以达到最佳的视觉效果。

收集整理了一份《2024年最新Python全套学习资料》免费送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。 img img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Python知识点,真正体系化!

了解详情:docs.qq.com/doc/DSnl3ZG…