image python ajouter du texte

   PIL peut ajouter du texte à la position désignée de l'image. L'ajout d'un ou deux mots à l'image est très simple à mettre en œuvre. Si vous voulez écrire une longue histoire dans l'image, c'est un peu compliqué. Vous devez vous assurer que chaque autre partie écrit ce paragraphe de texte, puis écrire dans mon texte Traitement des segments, puis les écrire dans l'image morceau par morceau. Cette méthode peut éviter d'ajouter un petit mot et de rendre le texte désordonné. Ce qui suit présente respectivement l'insertion simple de texte et la méthode d'insertion de texte dans les sections.

        La première consiste simplement à insérer du texte:

              # - * - codage: 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()运行结果如下图:

           

        La seconde consiste à segmenter les données écrites, puis à déterminer une certaine position de l'image écrite. Parmi eux, un paragraphe de texte est segmenté, je suis sur Baidu sur Internet et j'ai cité les scripts d'autres personnes. https://www.jb51.net/article/153901.htm, merci beaucoup à l'auteur de cet 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("微笑")

Les résultats de l'opération sont les suivants:

   

  

   

Je suppose que tu aimes

Origine blog.csdn.net/xxy_yang/article/details/86574059
conseillé
Classement