鱼C论坛

 找回密码
 立即注册
查看: 517|回复: 0

随机选取字体和内容,用PIL在空白图片上打印文字,遇到了FileNotFoundError,求助

[复制链接]
发表于 2020-5-27 15:43:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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,真的不知道如何解决这个问题了,特此求助各位,谢谢~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-1-21 00:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表