imagen de python agregar texto

   PIL puede agregar texto en la posición designada de la imagen. Simplemente agregar una o dos palabras a la imagen es muy sencillo de implementar. Si desea escribir una historia larga en la imagen, esto es un poco complicado. Debe asegurarse de que cada una de las partes escriba ese párrafo de texto y luego escribir en mi texto Procesamiento de segmentos y luego escribirlos en la imagen pieza por pieza.Este método puede evitar agregar una pequeña palabra y hacer que el texto sea desordenado. A continuación, se presenta, respectivamente, la inserción simple de texto y el método de inserción de texto en secciones.

        Uno es simplemente insertar texto:

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

           

        El segundo es segmentar los datos escritos y luego determinar una cierta posición de la imagen escrita. Entre ellos, un párrafo de texto está segmentado Estoy en Baidu en Internet y cité los guiones de otras personas. https://www.jb51.net/article/153901.htm, muchas gracias al autor de este artículo.

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("微笑")

Los resultados de la operación son los siguientes:

   

  

   

Supongo que te gusta

Origin blog.csdn.net/xxy_yang/article/details/86574059
Recomendado
Clasificación