网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

python实现图片插入文字-创新互联

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

创新互联主要从事成都网站设计、成都网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务琼山,10多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792

问题

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

效果

原始图

注明

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

实现方式

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实现图片插入文字-创新互联
路径分享:http://bjjierui.cn/article/dhhhdi.html

其他资讯