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

yipeiwu_com5年前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 稀疏矩阵-sparse 存储和转换

Python 稀疏矩阵-sparse 存储和转换

稀疏矩阵-sparsep from scipy import sparse 稀疏矩阵的储存形式 在科学与工程领域中求解线性模型时经常出现许多大型的矩阵,这些矩阵中大部分的元素都为0...

详解Python字符串对象的实现

详解Python字符串对象的实现

PyStringObject 结构体 Python 中的字符串对象在内部对应一个名叫 PyStringObject 的结构体。“ob_shash” 对应字符串经计算过的 hash值, “...

python实现分析apache和nginx日志文件并输出访客ip列表的方法

本文实例讲述了python实现分析apache和nginx日志文件并输出访客ip列表的方法。分享给大家供大家参考。具体如下: 这里使用python分析apache和nginx日志文件输出...

python实现微信接口(itchat)详细介绍

前言 itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机器人。当然,该api的使用远不止一个机器...

python中的编码知识整理汇总

问题 在平时工作中,遇到了这样的错误: UnicodeDecodeError: 'ascii' codec can't decode byte 想必大家也都碰到过,很常见 。于是...