教程集 www.jiaochengji.com
教程集 >  Python编程  >  python进阶  >  正文 Python脚本绘制验证码

Python脚本绘制验证码

发布时间:2021-01-26   编辑:jiaochengji.com
教程集为您提供Python脚本绘制验证码等资源,欢迎您收藏本站,我们将为您提供最新的Python脚本绘制验证码资源

在Python中有个强大的绘图库pil,可以实现验证码的绘制功能。

PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。

由于PIL仅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow。

例讲述了python使用pil生成图片验证码的方法。分享给大家供大家参考。具体实现方法如下:

# -*- coding: utf-8 -*-
#导入三个模块
import Image,ImageDraw,ImageFont
import random
import math
'''基本功能'''
#图片宽度
width = 100
#图片高度
height = 40
#背景颜色
bgcolor = (255,255,255)
#生成背景图片
image = Image.new('RGB',(width,height),bgcolor)
#加载字体
font = ImageFont.truetype('FreeSans.ttf',30)
#字体颜色
fontcolor = (0,0,0)
#产生draw对象,draw是一些算法的集合
draw = ImageDraw.Draw(image)
#画字体,(0,0)是起始位置
draw.text((0,0),'1234',font=font,fill=fontcolor)
#释放draw
del draw
#保存原始版本
image.save('1234_1.jpeg')
'''演示扭曲,需要新建一个图片对象'''
#新图片
newImage = Image.new('RGB',(width,height),bgcolor)
#load像素
newPix = newImage.load()
pix = image.load()
offset = 0
for y in range(0,height):
  offset  = 1
  for x in range(0,width):
    #新的x坐标点
    newx = x   offset
    #你可以试试如下的效果
    #newx = x   math.sin(float(y)/10)*10
    if newx < width:            
      #把源像素通过偏移到新的像素点
      newPix[newx,y] = pix[x,y]
#保存扭曲后的版本      
newImage.save('1234_2.jpeg')
'''形变一下'''
#x1 = ax by c
#y1 = dx ey f
newImage = image.transform((width 30,height 10), Image.AFFINE, (1,-0.3,0,-0.1,1,0))
newImage.save('1234_3.jpeg')
'''画干扰线,别画太多,免得用户都看不清楚'''    
#创建draw,画线用
draw = ImageDraw.Draw(newImage)
#线的颜色
linecolor= (0,0,0)
for i in range(0,15):
  #都是随机的
  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)], linecolor)      
#保存到本地
newImage.save('1234_4.jpeg')

您可能感兴趣的文章:
php图片验证码的例子
php点击验证码实时刷新的实现代码
如何使用canvas的得到验证码的效果(附源码)
Python脚本绘制验证码
html5使用canva实现验证码效果(代码实例)
如何用PHP语言绘制多样字符验证码
python开发工程师是做什么的
php5中文图片验证码的制作方法
想用Python生成验证码,还得看这篇文章
php绘图不显示图片怎么办

[关闭]
~ ~