最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python在圖片中插入大量文字并且自動(dòng)換行

 更新時(shí)間:2019年01月02日 15:32:14   作者:staHuri  
今天小編就為大家分享一篇關(guān)于Python在圖片中插入大量文字并且自動(dòng)換行,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧

問題

如何在圖片中插入大量文字并且自動(dòng)換行

效果

原始圖

效果圖

注明

若需要寫入中文請(qǐng)使用中文字體

實(shí)現(xiàn)方式

from PIL import Image, ImageDraw, ImageFont
class ImgText:
  font = ImageFont.truetype("micross.ttf", 24)
  def __init__(self, text):
    # 預(yù)設(shè)寬度 可以修改成你需要的圖片寬度
    self.width = 100
    # 文本
    self.text = text
    # 段落 , 行數(shù), 行高
    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: # 超過預(yù)設(shè)寬度就修改段落 以及當(dāng)前行數(shù)
        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):
    # 按規(guī)定寬度分組
    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()

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接

相關(guān)文章

最新評(píng)論

麻江县| 同心县| 衡水市| 平安县| 紫云| 大丰市| 沈丘县| 永城市| 乐安县| 安塞县| 耒阳市| 永济市| 上高县| 宝鸡市| 桂平市| 江华| 罗平县| 大城县| 黄石市| 黑山县| 内黄县| 天台县| 隆尧县| 双辽市| 永新县| 滨州市| 安义县| 鄢陵县| 鄱阳县| 文化| 鲁山县| 驻马店市| 漳浦县| 灌南县| 安化县| 棋牌| 丹东市| 内黄县| 张家口市| 基隆市| 鄂托克前旗|