zoukankan      html  css  js  c++  java
  • 随机生成简单验证码

     1 from PIL import Image,ImageFont,ImageDraw,ImageFilter
     2 import random
     3 import string
     4 import sys
     5 import math
     6 
     7 numbers=4
     8 size=(150,60)
     9 bgcolor=(255,255,255)
    10 font_color=(0,0,0)
    11 draw_line=True
    12 line_numbers=(1,5)
    13 
    14  
    15 
    16 def bgfontrange():
    17   global bgcolor
    18   color1=random.randint(0,255)
    19   color2=random.randint(0,255)
    20   color3=random.randint(0,255)
    21   bgcolor=(color1,color2,color3)
    22 
    23 def ftfontrange():
    24   global font_color
    25   color1=random.randint(0,255)
    26   color2=random.randint(0,255)
    27   color3=random.randint(0,255)
    28   font_color=(color1,color2,color3)
    29 
    30  
    31 
    32  
    33 
    34 #生成一个写字函数
    35 
    36 def make_text():
    37   source=[str(x) for x in range(0,10)]
    38   source2=list(string.ascii_letters)
    39   source.extend(source2)
    40   return ''.join(random.sample(source,numbers))
    41 
    42  
    43 
    44 #生成一个划线函数
    45 
    46 def make_line(draw,width,height):
    47   begin=(random.randint(0,width),random.randint(0,height))
    48   end=(random.randint(0,width),random.randint(0,height))
    49   draw.line([begin,end],fill=font_color,width=3)
    50 
    51 #生成验证码
    52 def make_codepng():
    53   width,height=size #图片的宽度和高度
    54   image=Image.new(mode='RGB',size=(width,height),color=bgcolor) #创建图片
    55   draw=ImageDraw.Draw(image) #绘图工具
    56   text=make_text() #生成随机字符串
    57   font=ImageFont.truetype('simhei.ttf',40)
    58   font_width,font_height=font.getsize(text) #得到字体的宽度和高度
    59   draw.text(((width-font_width)/numbers,height-font_height),text,font=font,fill=font_color) #写入文字
    60 if draw_line:
    61   make_line(draw,width,height)
    62 
    63   image=image.transform((width+40,height+30),Image.AFFINE,(1,-0.5,0,-0.2,0.9,0),Image.BILINEAR) #扭曲
    64   image=image.filter(ImageFilter.EDGE_ENHANCE_MORE) #处理边界
    65   image.save(r"D:计算机二级验证码"+"\"+text+".png")
    66 for i in range(100):
    67   bgfontrange()
    68 
    69   ftfontrange()
    70 
    71   make_codepng()
  • 相关阅读:
    异常
    C++中的mutable,volatile,explicit关键字
    Vi配置文件--Vimrc
    结构体和类的区别
    [转]恢复视力的方法(500度以下)
    与struct相关的宏定义 ---今Tencent笔试用到的
    如何在C++中调用C的代码
    C中如何调用C++函数?
    技术博走起
    Shell常见命令实践
  • 原文地址:https://www.cnblogs.com/energetic/p/13044716.html
Copyright © 2011-2022 走看看