代码:
import random,string
from PIL import Image,ImageDraw,ImageFont
#生成随机字母
lists=list(string.ascii_letters)
keys=random.sample(lists,4)
#生成随机颜色
def randomcolor():
colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
color = ""
for i in range(6):
color += colorArr[random.randint(0,14)]
return "#"+color
#生成图片
def newimage():
img=Image.open('timg.jpg')
#加载TrueType或OpenType字体文件,并创建一个字体对象。
newi=img.resize((240,60))
#newi.show()
draw = ImageDraw.Draw(newi)
font1 = ImageFont.truetype(r'C:\Windows\Fonts\ahronbd.ttf',36)
fillcolor = "#ff0000"
width, height = newi.size
draw.text((width/2-60,height/2-20),keys[0], font=font1, fill=randomcolor())
draw.text((width/2-30,height/2-20),keys[1], font=font1, fill=randomcolor())
draw.text((width/2,height/2-20),keys[2], font=font1, fill=randomcolor())
draw.text((width/2+30,height/2-20),keys[3], font=font1, fill=randomcolor())
newi.save('result.jpg','jpeg')
newi.show()
newimage()
运行截图: