脚本专栏 
首页 > 脚本专栏 > 浏览文章

python实现图片插入文字

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

本文实例为大家分享了python图片插入文字的具体代码,供大家参考,具体内容如下

问题

如何在图片中插入大量文字并且自动换行

效果

原始图

python实现图片插入文字

效果图

python实现图片插入文字

注明

若需要写入中文请使用中文字体

实现方式

from PIL import Image, ImageDraw, ImageFont


class ImgText:
  font = ImageFont.truetype("micross.ttf", 24)

  def __init__(self, text):
    # 预设宽度 可以修改成你需要的图片宽度
    self.width = 100
    # 文本
    self.text = text
    # 段落 , 行数, 行高
    self.duanluo, self.note_height, self.line_height = self.split_text()

  def get_duanluo(self, text):
    txt = Image.new('RGBA', (100, 100), (255, 255, 255, 0))
    draw = ImageDraw.Draw(txt)
    # 所有文字的段落
    duanluo = ""
    # 宽度总和
    sum_width = 0
    # 几行
    line_count = 1
    # 行高
    line_height = 0
    for char in text:
      width, height = draw.textsize(char, ImgText.font)
      sum_width += width
      if sum_width > self.width: # 超过预设宽度就修改段落 以及当前行数
        line_count += 1
        sum_width = 0
        duanluo += '\n'
      duanluo += char
      line_height = max(height, line_height)
    if not duanluo.endswith('\n'):
      duanluo += '\n'
    return duanluo, line_height, line_count

  def split_text(self):
    # 按规定宽度分组
    max_line_height, total_lines = 0, 0
    allText = []
    for text in self.text.split('\n'):
      duanluo, line_height, line_count = self.get_duanluo(text)
      max_line_height = max(line_height, max_line_height)
      total_lines += line_count
      allText.append((duanluo, line_count))
    line_height = max_line_height
    total_height = total_lines * line_height
    return allText, total_height, line_height

  def draw_text(self):
    """
    绘图以及文字
    :return:
    """
    note_img = Image.open("001.png").convert("RGBA")
    draw = ImageDraw.Draw(note_img)
    # 左上角开始
    x, y = 0, 0
    for duanluo, line_count in self.duanluo:
      draw.text((x, y), duanluo, fill=(255, 0, 0), font=ImgText.font)
      y += self.line_height * line_count
    note_img.save("result.png")


if __name__ == '__main__':
  n = ImgText(
    "1234567890" * 5)
  n.draw_text()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:使用Python实现 学生学籍管理系统
下一篇:python NumPy ndarray二维数组 按照行列求平均实例
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网