扣丁学堂Python培训简述Python如何在图片中插入大量文字且自动换行

2019-03-27 13:57:50 993浏览

本篇文章扣丁学堂Python培训小编和喜欢Python开发技术的小伙伴们分享一下Python开发技术:Python如何在图片中插入大量文字且自动换行,小编觉得有很好的参考价值,现在分享给小伙伴们,希望对小伙伴有所帮助。

扣丁学堂Python培训简述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如何在图片中插入大量文字且自动换行,希望对小伙伴们有所帮助,想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询。


想要学好Python开发小编给大家推荐口碑良好的扣丁学堂,扣丁学堂有专业老师制定的Python学习路线图辅助学员学习,此外还有与时俱进的Python视频教程供大家学习,想要学好Python开发技术的小伙伴快快行动吧。扣丁学堂Python技术交流群:279521237。


扣丁学堂微信公众号                          Python全栈开发爬虫人工智能机器学习数据分析免费公开课直播间


【关注微信公众号获取更多学习资料】         【扫码进入Python全栈开发免费公开课】



查看更多关于"Python开发资讯"的相关文章>



标签: Python培训 Python视频教程 Python在线视频 Python学习视频 Python培训班

热门专区

暂无热门资讯

课程推荐

微信
微博
15311698296

全国免费咨询热线

邮箱:codingke@1000phone.com

官方群:148715490

北京千锋互联科技有限公司版权所有   北京市海淀区宝盛北里西区28号中关村智诚科创大厦4层
京ICP备12003911号-6   Copyright © 2013 - 2019

京公网安备 11010802030908号