温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用python怎么生成一个图形验证码

发布时间:2021-04-12 17:38:47 来源:亿速云 阅读:133 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关使用python怎么生成一个图形验证码,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

主要用到的库--PIL图像处理库,简单的思路,我们需要随机的颜色,随机的数字或字母,随机的线条、点作为干扰元素 拼凑成一张图片。

生成随机颜色,返回的是rgb三色。

def getRandomColor():
  r = random.randint(0, 255)
  g = random.randint(0, 255)
  b = random.randint(0, 255)
  return (r, g, b)

从数字、大小写字母里生成随机字符。

def getRandomChar():
  random_num = str(random.randint(0, 9))
  random_lower = chr(random.randint(97, 122)) # 小写字母a~z
  random_upper = chr(random.randint(65, 90)) # 大写字母A~Z
  random_char = random.choice([random_num, random_lower, random_upper])
  return random_char

图片操作,生成一张随机背景色的图片,随机生成5种字符+5种颜色,在图片上描绘字,由于默认的字体很小,还需要对字进行处理,不同系统下的字体文件存放位置不一样,这里我是把window下的 arial.ttf 字体复制到了当前文件夹下直接使用的。

# 图片宽高
width = 160
height = 50

def createImg():
  bg_color = getRandomColor()
  # 创建一张随机背景色的图片
  img = Image.new(mode="RGB", size=(width, height), color=bg_color)
  # 获取图片画笔,用于描绘字
  draw = ImageDraw.Draw(img)
  # 修改字体
  font = ImageFont.truetype(font="arial.ttf", size=36)
  for i in range(5):
    # 随机生成5种字符+5种颜色
    random_txt = getRandomChar()
    txt_color = getRandomColor()
    # 避免文字颜色和背景色一致重合
    while txt_color == bg_color:
      txt_color = getRandomColor()
    # 根据坐标填充文字
    draw.text((10 + 30 * i, 3), text=random_txt, fill=txt_color, font=font)
  # 打开图片操作,并保存在当前文件夹下
  with open("test.png", "wb") as f:
    img.save(f, format="png")

这个时候可以看到文件夹下面的图片

使用python怎么生成一个图形验证码

这里是张很清晰的图片,为了有干扰元素,这里还需要在图片加入些线条、点作为干扰点。

随机画线,在图片宽高范围内随机生成2个坐标点,并通过随机颜色产生线条。

def drawLine(draw):
  for i in range(5):
    x1 = random.randint(0, width)
    x2 = random.randint(0, width)
    y1 = random.randint(0, height)
    y2 = random.randint(0, height)
    draw.line((x1, y1, x2, y2), fill=getRandomColor())

随机画点,随机生成横纵坐标点。

def drawPoint(draw):
  for i in range(50):
    x = random.randint(0, width)
    y = random.randint(0, height)
    draw.point((x,y), fill=getRandomColor())

生成方法

def createImg():
  bg_color = getRandomColor()
  # 创建一张随机背景色的图片
  img = Image.new(mode="RGB", size=(width, height), color=bg_color)
  # 获取图片画笔,用于描绘字
  draw = ImageDraw.Draw(img)
  # 修改字体
  font = ImageFont.truetype(font="arial.ttf", size=36)
  for i in range(5):
    # 随机生成5种字符+5种颜色
    random_txt = getRandomChar()
    txt_color = getRandomColor()
    # 避免文字颜色和背景色一致重合
    while txt_color == bg_color:
      txt_color = getRandomColor()
    # 根据坐标填充文字
    draw.text((10 + 30 * i, 3), text=random_txt, fill=txt_color, font=font)
  # 画干扰线点
  drawLine(draw)
  drawPoint(draw)
  # 打开图片操作,并保存在当前文件夹下
  with open("test.png", "wb") as f:
    img.save(f, format="png")

关于使用python怎么生成一个图形验证码就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI