新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

使用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怎么在图片中插入大量文字就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


本文标题:使用Python怎么在图片中插入大量文字-创新互联
转载来源:http://www.wjwzjz.com/article/djejoc.html
在线咨询
服务热线
服务热线:028-86922220
TOP