python picture add text

   PIL can add some text in the designated position of the picture. Simply adding one or two words to the picture is very simple to implement. If you want to write a long story in the picture, this is a bit complicated. You need to make sure that each other party writes that paragraph of text, and then write to my text Segment processing, and then write them into the picture piece by piece. This method can avoid adding words a little bit and causing the text to be messy. The following respectively introduces the simple insertion of text and the method of inserting text in sections.

        One is to simply insert text:

              # -*- coding:utf-8 -*-

       from PIL import Image,ImageDraw,ImageFont
       old_img = Image.open(r"cat.jpeg")
       # 输出图片的大小
        X,Y = old_img.size
       # 图片旋转
       new_image = old_img.resize((300,300),Image.ANTIALIAS).transpose(Image.ROTATE_90)
       draw = ImageDraw.Draw(new_image)
       # 设置图片文字,字体类型,以及字体大小
       newfont=ImageFont.truetype('simkai.ttf',20)
       #draw.txt:向图片中写入文字,x,y是确定写入文字的位置,font文字大小,file字体颜色
       draw.text((40,150),"要抱抱",font=newfont,fill="blue")
        new_image.show()运行结果如下图:

           

        The second is to segment the written data, and then determine a certain position of the written picture. Among them, a paragraph of text is segmented. I am on Baidu on the Internet and quoted someone else's script. https://www.jb51.net/article/153901.htm, thank you very much to the author of this article.

from PIL import Image, ImageDraw, ImageFont

class ImgText:

    microsoft_bold = ImageFont.truetype('simkai.ttf',20)

    def __init__(self, text,width):
        # 预设宽度 可以修改成你需要的图片宽度
        self.width = width
        # 文本
        self.text = text
        # 段落 , 行数, 行高
        self.duanluo, self.note_height, self.line_height = self.split_text()

    def get_duanluo(self, text):
        txt = Image.new('RGBA', (50, 300), (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.microsoft_bold)
            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):
        pass


 #主要是对分好段的数据,一次写入图片中
    def draw_summary(self,file_name):
        x, y = 30, 100
        note_img = Image.open("cat.jpeg").convert("RGBA")
        draw = ImageDraw.Draw(note_img)
        #获取分好段的列表数据
        duanluo_datas = [i for i in self.duanluo[0]]
       # 一段文字可以分成几段
        line_count= duanluo_datas[-1]
        print(line_count)
        txt_datas= duanluo_datas[0].split("\n")
        first_txt = txt_datas[0]
        precent_txt = first_txt.split(file_name)[1]
       #写入第一段文字,开始的位置为设定的位置,写入蓝色字体的微笑,然后获取微笑的width,height
        draw.text((x,y),file_name,fill="blue", font=ImgText.microsoft_bold)
        width, height = draw.textsize(file_name, ImgText.microsoft_bold)
        #接着微笑在写入字段,开始是微笑字段的长度加上x
        draw.text((x+width,y),precent_txt,fill="white", font=ImgText.microsoft_bold)
        # 第二段写入数据。第二段写入的开始位置不变,然而他的高度变成原来的高度,加上微笑的高度
        draw.text((x,y+height),txt_datas[1],fill="white", font=ImgText.microsoft_bold)
        note_img.show()
if __name__ == '__main__':
    n = ImgText("微笑在天上飞,你说你有点难追,想让我知难而退,礼物不需挑最贵,只要香榭的落叶。",500)
    n.draw_summary("微笑")

The results of the operation are as follows:

   

  

   

Guess you like

Origin blog.csdn.net/xxy_yang/article/details/86574059