本文是基于廖大官方网站Python3.5PIL节所写。来源廖雪峰的官方网站 。在此基础上增加了数字、汉字、字母。
代码如下:
from PIL import Image,ImageFilter,ImageDraw,ImageFont
import random
def rndChar():
numChr = str(random.randint(0,9))
letChr = chr(random.randint(65,90))
chChr =random.choice("中华文化博大精深")
return random.choice((numChr,letChr,chChr))
def rndColor():
return (random.randint(0,255),random.randint(0,255),random.randint(0,255))
width = 240
height = 60
image = Image.new('RGB',(width,height),(255,255,255))
font = ImageFont.truetype('C:\Windows\Fonts\simsun.ttc',40)
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.multiline_text((60*t+10,10),rndChar(),font=font,fill=rndColor2())
image = image.filter(ImageFilter.MinFilter)
image.save('code.jpeg','jpeg')