目录

批量将文字转变为JPEG图片

问题说明

我现在有一份人员名单列表,比如说,一份 txt 文本文件,每一行是一个人名,我需要将每一个人名,转换为一张图片。

问题细化

  1. 数据输入,这里比较简单,就是读取 names.txt 文件,文件里每一行就是一个人名,没有多余信息,类似这样:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
王建国
杨阳
陈华
杨华
王建军
杨柳
刘阳
王淑珍
杨芳
李春梅
刘俊
王海燕
  1. 图片格式要求,这里是 A4 纸大小的一个图片,目的是为了后续打印使用(A4纸的标准尺寸为: 210*297 毫米),人名要放大铺满 A4 纸的的大小。

  2. 图片保存到 names.txt 文件所在目录的 output 子目录下

程序实现

问题比较简单,有很多种解决办法,我这里使用 Python 程序来搞定。

读取文件数据

第一步是读取文件内容,这步比较简单:

1
2
with open(filename, "r") as f:
    data = f.readlines()

直接读取每一行内容,保存到一个数组,要注意这样读取的数据,最后面是一有个换行符的,要去掉。

生成图片内容

然后可以使用Python的Pillow库来实现文字画图功能。先安装Pillow库,可以使用pip install pillow来安装。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
    # 创建一个A4大小的白色图片
    image = Image.new('RGB', (2100, 2970), 'white')
    draw = ImageDraw.Draw(image)
    
    # 加载中文字体
    font = ImageFont.truetype('/System/Library/Fonts/PingFang.ttc', 36)
    
    # 计算文字的宽度和高度
    text_width, text_height = draw.textsize(name, font=font)
    
    # 计算文字的放置位置
    x = (2100 - text_width) / 2
    y = (2970 - text_height) / 2
    
    # 将人名写入图片
    draw.text((x, y), name, font=font, fill='black')

但是有一个问题,这里字体大小,是手工设置的36,图片里的中文字非常小。当然可以不断尝试,调整到合适的大小,但是因为人名,有长有短,从两个字到四五个字不等。

想要刚刚好人名铺满图片的效果,这里要动态调整字体大小。

可以通过不断增加字体大小,直到文字填满整个图片为止。核心处理逻辑如下:

1
2
3
4
5
6
7
8
9
    # 不断增加字体大小,直到文字填满整个图片
    font_size = 16
    while True:
        # 加载中文字体
        font = ImageFont.truetype(font_name, font_size)
        text_width, text_height = font.getsize(name)
        if text_width > image_width or text_height > image_height:
            break
        font_size += 1

这次得到的效果就OK了,每个人名都能完整的铺满整个图片宽度,如图:

text-to-image-1.zh-cn.webp
批量文字生成图片效果图

最终完整代码

最后附上完工后的完整Python代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import os
from PIL import Image, ImageDraw, ImageFont


def generate_name_image(name, number, output_path):
	# 注意!这里需要修改为你自己电脑上(你自己喜欢的)的字体文件
    font_name = '/System/Library/Fonts/PingFang.ttc'
    image_width = 2100
    image_height = 2970
    font_size = 16

    # 不断增加字体大小,直到文字填满整个图片
    while True:
        # 加载中文字体
        font = ImageFont.truetype(font_name, font_size)
        text_width, text_height = font.getsize(name)
        if text_width > image_width or text_height > image_height:
            break
        font_size += 1

    # 重新计算放置位置
    x = (image_width - text_width) / 2
    y = (image_height - text_height) / 2

    # 创建图片并将人名写入
    image = Image.new('RGB', (image_width, image_height), 'white')
    draw = ImageDraw.Draw(image)
    draw.text((x, y), name, font=font, fill='black')

    # 保存图片
    image.save(f'{output_path}/{number}.jpg')


def load_data(filename):
    output_path = "output"
    if not os.path.exists(output_path):  # 判断存放图片的文件夹是否存在
        os.makedirs(output_path)  # 若图片文件夹不存在就创建

    with open(filename, "r") as f:
        data = f.readlines()
        for i in range(len(data)):
            text = data[i].strip('\r\n ')  # 去掉列表中每一个元素的换行符
            # print(text)
            generate_name_image(text, i + 1, output_path)


load_data('names.txt')