|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
目的:在空白图片上打印文字
思路:1.选择一张空白图片作为底图
2.在准备好的txt文档中(文档有60行,每行用空行隔开的),随机选择一行文字
3.从准备好的字体文件夹中(文件夹中共有42种字体)随机选择一种字体
4.用PIL的ImageDraw生成,并保存
源代码:
- from PIL import Image, ImageDraw, ImageFont
- import os
- import random
- # 1.get an image
- path_of_image = r'C:\Users\Lenovo\Desktop\666\A4.jpg'
- bg_image = Image.open(path_of_image)
- # 2.get a txt
- path_of_txts =r'C:\Users\Lenovo\Desktop\22.txt'
- with open(path_of_txts, 'rb') as f:
- each_line = []
- for i, line in enumerate(f.readlines()):
- each_line.append(line)
- # 3.get a font
- path_of_fonts = r'C:\Users\Lenovo\Desktop\fonts\字体分类\A1_视重轻'
- list_of_font = os.listdir(path_of_fonts)
- num_of_select = 1
- list_of_random_font = random.sample(list_of_font, num_of_select)
- # 4.draw on the bg
- draw = ImageDraw.Draw(bg_image)
- choosen_font_size = ImageFont.truetype(list_of_random_font[0], 110)
- draw.text((500,1000), each_line, font=choosen_font_size, fill=(0, 0, 0))
- bg_image.save(r'C:\Users\Lenovo\Desktop\555', 'jpg')
复制代码
结果报错:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Lenovo/cvdemo/Project_CB/CB_04_字体生成A1.py", line 24, in <module>
choosen_font_size = ImageFont.truetype(list_of_random_font[0], 110)
File "C:\Users\Lenovo\cvdemo\venv\lib\site-packages\PIL\ImageFont.py", line 648, in truetype
return freetype(font)
File "C:\Users\Lenovo\cvdemo\venv\lib\site-packages\PIL\ImageFont.py", line 645, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Users\Lenovo\cvdemo\venv\lib\site-packages\PIL\ImageFont.py", line 190, in __init__
with open(font, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: '1 汉仪彩云体简.ttf'
小弟初学python,真的不知道如何解决这个问题了,特此求助各位,谢谢~
|
|