#!/usr/bin/env python
# coding: utf-8
# # 1.验证码的生成
# In[68]:
#coding=utf-8
import random,string, sys, math
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import matplotlib.pyplot as plt
font_path = r'C:\Windows\Fonts\simkai.ttf ' #字体的位置
number = 4 #生成几位数的验证码
size = (80,30) #生成验证码图片的高度和宽度
bgcolor = (0,255,255) #背景颜色,默认为白色
fontcolor = (0,0,255) #字体颜色,默认为蓝色
linecolor = (255,0,0) #干扰线颜色。默认为红色
draw_line = True #是否要加入干扰线
line_number = (1,5) #加入干扰线条数的上下限
#用来随机生成一个字符串
def gene_text():
#source = list(string.letters)
#source =[ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
source = list(string.ascii_letters)
for index in range(0,10):
source.append(str(index))
return ''.join(random.sample(source,number)) #number是生成验证码的位数
#用来绘制干扰线
def gene_line(draw,width,height):
begin = (random.randint(0, width), random.randint(0, height))
end = (random.randint(0, width), random.randint(0, height))
draw.line([begin, end], fill = linecolor)
#生成验证码
def gene_code():
width,height = size #宽和高
image = Image.new('RGBA',(width,height),bgcolor) #创建图片
font = ImageFont.truetype(font_path,25) #验证码的字体
draw = ImageDraw.Draw(image) #创建画笔
text = gene_text() #生成字符串
font_width = font.getlength(text)
font_height = font.getlength(text)
draw.text(((width - font_width) / number, (height - font_height) / number),text,
font= font,fill=fontcolor) #填充字符串
if draw_line:
gene_line(draw,width,height)
image = image.transform((width+20,height+10), Image.Transform.AFFINE,
(1,-0.3,0,-0.1,1,0),Image.Resampling.BILINEAR) #创建扭曲
image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #滤镜,边界加强
image.save(r'..\R&Q_pic\idencode.png') #保存验证码图片
plt.imshow(image) #在2D坐标系中绘制合成
plt.axis('off') #隐藏坐标轴
plt.show() #显示图片
if __name__ == "__main__": #程序入口声明:作为模块直接执行
gene_code() #函数调用
# # 2.打印ASCII字符
print('\n--------------------ASCII字符表-------------------\n')
count=0
for i in range(32,128):
print('[',i,']',chr(i),end=' ')
count+=1
if(count%5==0):
print('\n')