国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python在圖片中插入大量文字并且自動換行

2020-02-16 00:28:46
字體:
來源:轉載
供稿:網友

問題

如何在圖片中插入大量文字并且自動換行

效果

原始圖

效果圖

注明

若需要寫入中文請使用中文字體

實現方式

from PIL import Image, ImageDraw, ImageFontclass 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()

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林站長站的支持。如果你想了解更多相關內容請查看下面相關鏈接

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 瑞丽市| 广平县| 连州市| 台中市| 合水县| 历史| 弥渡县| 玉屏| 来安县| 通山县| 甘肃省| 和平区| 辽中县| 南乐县| 南昌县| 姚安县| 巢湖市| 安国市| 宝兴县| 阳朔县| 台州市| 新营市| 永州市| 阿鲁科尔沁旗| 佛冈县| 闵行区| 冀州市| 浙江省| 洞口县| 曲松县| 香河县| 长武县| 赫章县| 德钦县| 称多县| 雷波县| 台东市| 长子县| 万全县| 珠海市| 苍梧县|