代码如下:
from PIL import Image, ImageFilter, ImageFont, ImageDrawimport random# 随机字母
def rndChar():return chr(random.randint(65, 90))# 随机颜色1:
def rndColor():return random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)# 随机颜色2:
def rndColor2():return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)# 240 x 60
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象
font = ImageFont.truetype('Arial.ttf', 36)
# 创建Draw对象
draw = ImageDraw.Draw(image)
# 填充每个像素
for x in range(width):for y in range(height):draw.point((x, y), fill=rndColor())
# 输出文字
for t in range(4):draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')
执行报错:
"D:\Program Files\python-3.7.9\python.exe" D:/py/test-three/test_01.py
Traceback (most recent call last):File "D:/py/test-three/test_01.py", line 26, in <module>font = ImageFont.truetype('Arial.ttf', 36)File "D:\Program Files\python-3.7.9\lib\site-packages\PIL\ImageFont.py", line 844, in truetypereturn freetype(font)File "D:\Program Files\python-3.7.9\lib\site-packages\PIL\ImageFont.py", line 841, in freetypereturn FreeTypeFont(font, size, index, encoding, layout_engine)File "D:\Program Files\python-3.7.9\lib\site-packages\PIL\ImageFont.py", line 194, in __init__font, size, index, encoding, layout_engine=layout_engine
OSError: cannot open resource进程已结束,退出代码1
分析报错信息以及ImageFont.py中truetype源码,“:exception OSError: If the file could not be read.”,分析字体文件无法读取,可本地搜索字体,查看字体名称为“arial.ttf”,将“Arial.ttf”改为“arial.ttf”,执行成功,另一种解决方法就是获取字体绝对路径,如“C:\Windows\Fonts\Arial.ttf”,更换执行成功。