# coding:utf-8
from PIL import Image, ImageDraw, ImageFont
import textwrap
str_tu_ou = []
#打开你的txt文件,第一行必须是英文
with open("d:/TXT.txt", "r", encoding='utf-8') as f:
for line in f.readlines():
line = line.replace(' ', '')#把所有的空格给去掉
line = line.strip('\n') # 去掉列表中每一个元素的换行符
str_tu_ou.append(line)
ttf = ImageFont.truetype('d:/HarmonyOS_Sans_SC_Bold.ttf', 80)
#导入字体
draw = Image.open('d:/background.jpg')
#导入底图
num = 1
file_output = 'd:/picture/%s.jpg' % num #指定输出的路径
for i in str_tu_ou:
english = i[0].isupper() or i[0].islower()
width, height = draw.size
img = Image.open('d:/background.jpg')
if english:
word = textwrap.wrap(i, 42)
num_word = range(len(word))
for n in num_word:
w, h = ttf.getsize(word[n])
if n == 0:
print('正在输出英文语句:', i)
img_draw = ImageDraw.Draw(img)
width_en = 100
height_en = (height/2 - (len(word))*h)
img_draw = ImageDraw.Draw(img)
img_draw.text((width_en, height_en), word[n], font=ttf, fill=(255, 255, 255))
img.save(file_output)
height_en += h
else:
print('正在输出英文语句:', i)
img_draw = ImageDraw.Draw(img)
width_en = 100
height_en = (height / 2 - (len(word)) * h)
img_draw = ImageDraw.Draw(img)
img_draw.text((width_en, height_en), word[n], font=ttf, fill=(255, 255, 255))
img.save(file_output)
height_en += h
else:
word = textwrap.wrap(i, 21)
num_word = range(len(word))
height_zh = (height / 2 + h/2)
for n in num_word:
w, h = ttf.getsize(word[n])
print('正在输出中文语句:', i)
img_draw = ImageDraw.Draw(img)
img_draw.text((width_en, height_zh), word[n], font=ttf, fill=(255, 255, 255))
img.save(file_output)
height_zh += h + 10
num += 1
print('执行完毕')