python 实现text to img

技术 · 2023-03-03 · 37 人浏览

python 实现text to img

# coding=utf-8
from PIL import Image, ImageDraw, ImageFont

LINE_CHAR_COUNT = 50*2  # 每行字符数:30个中文字符(=60英文字符)
CHAR_SIZE = 30
TABLE_WIDTH = 4

def line_break(line):
    ret = ''
    width = 0
    for c in line:
        # print("c.encode('utf8')",c.encode('utf8'),"c",c)
        if len(c.encode('utf8')) == 3:  # 中文
            if LINE_CHAR_COUNT == width + 1:  # 剩余位置不够一个汉字
                width = 2
                ret += '\n' + c
            else: # 中文宽度加2,注意换行边界
                width += 2
                ret += c
        else:
            if c == '\t':
                space_c = TABLE_WIDTH - width % TABLE_WIDTH  # 已有长度对TABLE_WIDTH取余
                ret += ' ' * space_c
                width += space_c
            elif c == '\n':
                width = 0
                ret += c
            else:
                width += 1
                ret += c
        if width >= LINE_CHAR_COUNT:
            ret += '\n'
            width = 0
    if ret.endswith('\n'):
        return ret
    return ret + '\n'

def open_txt(text_file,lg):
    with open(text_file, encoding='utf-8') as file:
        content = file.read()
        print(content.rstrip())
    output_str = line_break(content)
    if lg=='ti':  # 藏文
        d_font = ImageFont.truetype('./font/himalaya.ttf', CHAR_SIZE)
    elif lg=='ar':  # 阿拉伯文
        d_font = ImageFont.truetype('./font/arial.ttf', CHAR_SIZE)
    elif lg == 'mo':  # 蒙文
        d_font = ImageFont.truetype('./font/OnonSoninSans.ttf', CHAR_SIZE)
    elif lg == 'ko':  # 韩文
        d_font = ImageFont.truetype('./font/malgun.ttf', CHAR_SIZE)
    elif lg == 'cht':  # 繁体
        d_font = ImageFont.truetype('./font/msjh.ttc', CHAR_SIZE)
    else: # 简体和英文
        d_font = ImageFont.truetype('./font/msyh.ttc', CHAR_SIZE)
    lines = output_str.count('\n')  # 计算行数

    image = Image.new('RGB', (LINE_CHAR_COUNT * CHAR_SIZE // 2 + 100, CHAR_SIZE * lines + 100), "white")
    draw_table = ImageDraw.Draw(im=image)
    draw_table.text(xy=(50, 50), text=output_str, fill='#000000', font=d_font)

    image.save('./image/'+lg+'.png', 'PNG')  # 保存在当前路径下,格式为PNG
    image.show()
    image.close()

lg=['ti','ar','mo','ko','cht','zh','en']
for i in lg:
    open_txt('./txt/'+i+'.txt', i)

进行了修改将图片保存在一张图片上本来想使用pngtosvg但是好像是清晰度太高了还是咋地 生成不出来

# coding=utf-8
from PIL import Image, ImageDraw, ImageFont
#from image import img_converter

LINE_CHAR_COUNT = 50*2  # 每行字符数:30个中文字符(=60英文字符)
CHAR_SIZE = 100
TABLE_WIDTH = 4

def line_break(line):
    ret = ''
    width = 0
    for c in line:
        # print("c.encode('utf8')",c.encode('utf8'),"c",c)
        if len(c.encode('utf8')) == 3:  # 中文
            if LINE_CHAR_COUNT == width + 1:  # 剩余位置不够一个汉字
                width = 2
                ret += '\n' + c
            else: # 中文宽度加2,注意换行边界
                width += 2
                ret += c
        else:
            if c == '\t':
                space_c = TABLE_WIDTH - width % TABLE_WIDTH  # 已有长度对TABLE_WIDTH取余
                ret += ' ' * space_c
                width += space_c
            elif c == '\n':
                width = 0
                ret += c
            else:
                width += 1
                ret += c
        if width >= LINE_CHAR_COUNT:
            ret += '\n'
            width = 0
    if ret.endswith('\n'):
        return ret
    return ret + '\n'

def open_txt(text_file,lg):
    with open(text_file, encoding='utf-8') as file:
        content = file.read()
        print(content.rstrip())
    output_str = line_break(content)
    if lg=='ti':  # 藏文
        d_font = ImageFont.truetype('./font/himalaya.ttf', CHAR_SIZE)
    elif lg=='ar':  # 阿拉伯文
        d_font = ImageFont.truetype('./font/arial.ttf', CHAR_SIZE)
    elif lg == 'mo':  # 蒙文
        d_font = ImageFont.truetype('./font/OnonSoninSans.ttf', CHAR_SIZE)
    elif lg == 'ko':  # 韩文
        d_font = ImageFont.truetype('./font/malgun.ttf', CHAR_SIZE)
    elif lg == 'cht':  # 繁体
        d_font = ImageFont.truetype('./font/msjh.ttc', CHAR_SIZE)
    else: # 简体和英文
        d_font = ImageFont.truetype('./font/msyh.ttc', CHAR_SIZE)
    lines = output_str.count('\n')  # 计算行数

    image = Image.new('RGB', (LINE_CHAR_COUNT * CHAR_SIZE // 5 , CHAR_SIZE * lines + 100), "white")
    draw_table = ImageDraw.Draw(im=image)
    draw_table.text(xy=(50, 50), text=output_str, fill='#000000', font=d_font)

    image.save('./image/'+lg+'.png', 'PNG')  # 保存在当前路径下,格式为PNG
    # image.show()
    image.close()

lg=['zh','ti','ar','mo','ko','cht','en']
imgs_size=0
bg_image =Image.new('RGB',(2000,1400),color='white')# 拼接图像底图
for i in lg:
    open_txt('./txt/'+i+'.txt', i)
    img=Image.open('./image/'+i+'.png')
    imgs_size+=img.size[1]
    # print("img:"+i+str(imgs_size)+"!!!")
    bg_image.paste(img, (0, imgs_size))

bg_image.save('./image/output.png',quality=100)
#img_converter.main('./image/cht')
python text to image
Theme Jasmine by Kent Liao