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

      工具        

    pillow模块

    安装:pip install pillow

      封装一个产生随机验证码的类      

     1 from PIL import Image, ImageDraw, ImageFont, ImageFilter
     2 import random
     3 
     4 
     5 class ConfirmCode(object):
     6 
     7     def __init__(self, width, height, save_path, font, font_size, distance):
     8         self.width = width
     9         self.height = height
    10         self.save_path = save_path
    11         self.font = font
    12         self.font_size = font_size
    13         self.distance = distance
    14 
    15     # 随机字母
    16     def rnd_char(self):
    17         return chr(random.randint(65, 90))
    18 
    19     # 背景颜色
    20     def bg_color(self):
    21         return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
    22 
    23     # 文字颜色
    24     def text_color(self):
    25         return (random.randint(37, 127), random.randint(37, 137), random.randint(37, 137))
    26 
    27     # 生成验证码图片
    28     def code_image(self):
    29         image = Image.new("RGB", (self.width, self.height), (255, 255, 255))
    30         # 创建Font对象
    31         font = ImageFont.truetype(self.font, self.font_size)
    32         # 创建Draw对象
    33         draw = ImageDraw.Draw(image)
    34         # 填充每一个像素
    35         for x in range(self.width):
    36             for y in range(self.height):
    37                 draw.point((x, y), fill=self.bg_color())
    38         # 输出文字
    39         # 计算每个字体大小
    40         size = self.width / 4
    41         for t in range(4):
    42             draw.text((size*t + self.distance, 10), self.rnd_char(), font=font, fill=self.text_color())
    43         # 模糊
    44         image = image.filter(ImageFilter.BLUR)
    45         image.save(self.save_path, "jpeg")
    46 
    47 
    48 
    49 # 使用
    50 obj = ConfirmCode(240, 60, "code.jpg", 'arial.ttf', 38, 20)
    51 obj.code_image()

    参数

    • 生成验证码区域的宽度
    • height: 生成验证码区域的高度
    • save_path: 保存图片的路径
    • font: 字体样式
    • font_size: 字体大小
    • distance: 每个字之间的间距大小

    效果图

  • 相关阅读:
    新手Cocoa&Objectivec的进阶
    设计模式六大原则
    仿IOS Launch 欢迎界面
    新手开发IOS的疑惑,待补充
    Windows xp系统Hal.dll文件损坏的解决办法
    上班五年了!总结一下收获篇
    关于理财:摘自“华夏基金网”
    《雪》
    上班五年了!总结一下性格篇
    索尼爱立信M608C使用心得!
  • 原文地址:https://www.cnblogs.com/Myarticles/p/8904325.html
Copyright © 2011-2022 走看看