python PIL库报错还是
安装了pillow的
运行报错为
Traceback (most recent call last):
File "c:\Users\123\Desktop\Untitled-555.py", line 65, in <module>
main((200,100),8,(255,255,255))
File "c:\Users\123\Desktop\Untitled-555.py", line 26, in main
font=ImageFont.truetype('d:\python\times.ttf',48)
File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\ImageFont.py", line 976, in truetype
return freetype(font)
File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\ImageFont.py", line 973, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\ImageFont.py", line 249, in __init__
self.font = core.getfont(
OSError: cannot open resource
PS C:\Users\123>
代码
from importlib.machinery import OPTIMIZED_BYTECODE_SUFFIXES
import random
import string
from tkinter import OFF
from turtle import position
from xml.dom.pulldom import CHARACTERS
from PIL import Image, ImageDraw, ImageFont
characters=string.ascii_letters+string.digits
def selectCharacters(length):
result=""
for i in range(length):
result+=random.choice(characters)
return result
def getColor():
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
return (r, g, b)
def main(size=(200,100),characterNumber=6,bgcolor=(255,255,255)):
imageTemp=Image.new('RGB',size,bgcolor)
font=ImageFont.truetype('d:\python\times.ttf',48)
draw=ImageDraw.Draw(imageTemp)
text=selectedCharacters(characterNumber)
width,hight=draw.textsize(text,font)
offset=2
for i in range(characterNumber):
offset+=width//characterNumber
position=(offset,(size[1]-height)//2+random.randint(-10,10))
draw.text(xy=position,text=text[i],font=font,fill=getColor())
imageFinal=Image.new('RGB',size,bgcolor)
pixelsFinal=imageFinal.load()
for y in range(0,size[1]):
offset=random.randint(-1,1)
for x in range(0,size[0]):
newx=x+offset
if newx>size[0]:
newx=size[0]-1
elif newx<0:
newx=0
pixelsFinal[newx,y]=pixelsTemp[x,y]
draw=ImageDraw.Draw(imageFinal)
for i in range(int(size[0]*size[1]*0.07)):
draw.point((random.randint(0,size[0]),random.randint(0,size[1])),fill=getColor)
for i in range(8):
start=(0,random.randint(0,size[1]))
end=(size[0],random.randint(0,size[1]-1))
draw.line([star,end],fill=getColor(),width=1)
for i in range(8):
start=(-50,50)
end=(size[0]+10,random.randint(0,size[1]+10))
draw.arc(start+end,0,360,fill=getColor())
imageFinal.save('result.jpg')
imageFinal.show()
if __name__=='__main__':
main((200,100),8,(255,255,255))