python练习七十:图片生成
题目:使用python生成类似于下图的字母验证码图片
实现代码:
from PIL import Image,ImageFont,ImageDraw,ImageFilter import random #随机字母 def randChar(): return chr(random.randint(65,90)) #随机颜色1 def randColor(): return (random.randint(64,255),random.randint(64,255),random.randint(64,255)) #随机颜色2 def randColor2(): return (random.randint(32,127),random.randint(32,127),random.randint(32,127)) width,height = 240,60 #定义画布大小 image = Image.new("RGB",(width,height),(255,255,255)) #创建Font对象 font = ImageFont.truetype("C:\Windows\Fonts\ITCBLKAD.TTF",36) #字体必须是ttf格式 draw = ImageDraw.Draw(image) #创建Draw对象 #填充每个像素 for x in range(width): for y in range(height): draw.point((x,y),fill=randColor()) #生成文字 for t in range(4): draw.text((60*t + 10,10),randChar(),font=font,fill=randColor2()) image = image.filter(ImageFilter.BLUR)#模糊处理 image.save('text.jpg',"jpeg")