python PIL模块与随机生成中文验证码


Posted in Python onFebruary 27, 2016

在这之前,你首先得了解Python中的PIL库。PIL是Python Imaging Library的简称,PIL是一个Python处理图片的库,提供了一系列模块和方法,比如:裁切,平移,旋转,改变尺寸等等。在PIL库中,任何一个图像都是用Image对象来表示的,所以要加载一张图片,最简单的形式如下:

from PIL import Image
image = Image.open("1.jpeg")

在PIL库中,最常用的模块有Image,ImageDraw,ImageEnhance,ImageFile等。
PIL的下载地址为:http://www.pythonware.com/products/pil/
接下来学习PIL中一些常见的操作:

(1)改变图片大小

from PIL import Image

image = Image.open("1.jpeg")
new_img = image.resize((256,256),Image.BILINEAR)
new_img.save("2.jpeg")

(2)旋转图片

from PIL import Image

image = Image.open("1.jpeg")
new_img = image.rotate(45)
new_img.save("2.jpeg")

(3)直线绘制

PIL库中的ImageDraw模块提供了图形绘制的基本功能,可以绘制直线,弧线,椭圆,矩形等等。

from PIL import Image,ImageDraw

image = Image.open("2.jpeg")
draw = ImageDraw.Draw(image)
width,height = image.size
draw.line(((0,0),(width-1,height-1)),fill=255)
draw.line(((0,height-1),(width-1,0)),fill=255)
image.save("2.jpeg")

(4)绘制圆

from PIL import Image,ImageDraw

image = Image.open("2.jpeg")
draw = ImageDraw.Draw(image)
width,height = image.size
draw.arc((0,0,width-1,height-1),0,360,fill=255)
image.save("2.jpeg")

更多方法可以参见帮助文档。

现在我们来研究利用Python如何生成中文验证码。其实这个问题简单,我们都知道验证码一般是用来防止网络机器

人采用无限次数的登录尝试破解密码,那么我们需要对这张图片随机生成中文字符来验证,一般来说会把图片的字表

现得很模糊,这样有效地防止机器人识别。所以我们除了要随机生成汉字,还要加入一些干扰线条等等。

# -*- coding: utf-8 -*-
from PIL import Image,ImageDraw,ImageFont
import random
import math, string 

class RandomChar():
 @staticmethod
 def Unicode():
  val = random.randint(0x4E00, 0x9FBF)
  return unichr(val) 

 @staticmethod
 def GB2312():
  head = random.randint(0xB0, 0xCF)
  body = random.randint(0xA, 0xF)
  tail = random.randint(0, 0xF)
  val = ( head << 8 ) | (body << 4) | tail
  str = "%x" % val
  return str.decode('hex').decode('gb2312') 

class ImageChar:
 def __init__(self, fontColor = (0, 0, 0),
           size = (100, 40),
           fontPath = 'SIMSUN.TTC',
           bgColor = (255, 255, 255),
           fontSize = 20):
  self.size = size
  self.fontPath = fontPath
  self.bgColor = bgColor
  self.fontSize = fontSize
  self.fontColor = fontColor
  self.font = ImageFont.truetype(self.fontPath, self.fontSize)
  self.image = Image.new('RGB', size, bgColor) 

 def rotate(self):
  self.image.rotate(random.randint(0, 30), expand=0) 

 def drawText(self, pos, txt, fill):
  draw = ImageDraw.Draw(self.image)
  draw.text(pos, txt, font=self.font, fill=fill)

 def randRGB(self):
  return (random.randint(0, 255),
      random.randint(0, 255),
      random.randint(0, 255)) 

 def randPoint(self):
  (width, height) = self.size
  return (random.randint(0, width), random.randint(0, height)) 

 def randLine(self, num):
  draw = ImageDraw.Draw(self.image)
  for i in range(0, num):
   draw.line([self.randPoint(), self.randPoint()], self.randRGB())

 def randChinese(self, num):
  gap = 5
  start = 0
  for i in range(0, num):
   char = RandomChar().GB2312()
   x = start + self.fontSize * i + random.randint(0, gap) + gap * i
   self.drawText((x, random.randint(-5, 5)), RandomChar().GB2312(), self.randRGB())
   self.rotate()
  self.randLine(18) 

 def save(self, path):
  self.image.save(path)

ic = ImageChar(fontColor=(100,211, 90))
ic.randChinese(4)
ic.save("1.jpeg")

运行结果:

python PIL模块与随机生成中文验证码

Python 相关文章推荐
Python中函数及默认参数的定义与调用操作实例分析
Jul 25 Python
教你学会使用Python正则表达式
Sep 07 Python
Python脚本完成post接口测试的实例
Dec 17 Python
在django view中给form传入参数的例子
Jul 19 Python
pytorch神经网络之卷积层与全连接层参数的设置方法
Aug 18 Python
使用matplotlib绘制图例标签中带有公式的图
Dec 13 Python
Python restful框架接口开发实现
Apr 13 Python
Pycharm 使用 Pipenv 新建的虚拟环境(图文详解)
Apr 16 Python
Python使用Numpy模块读取文件并绘制图片
May 13 Python
简单了解Python多态与属性运行原理
Jun 15 Python
Python自带的IDE在哪里
Jul 01 Python
python 爬取百度文库并下载(免费文章限定)
Dec 04 Python
Pythont特殊语法filter,map,reduce,apply使用方法
Feb 27 #Python
python 网络爬虫初级实现代码
Feb 27 #Python
Python数据库的连接实现方法与注意事项
Feb 27 #Python
学习python之编写简单简单连接数据库并执行查询操作
Feb 27 #Python
学习python之编写简单乘法口诀表实现代码
Feb 27 #Python
学习python 之编写简单乘法运算题
Feb 27 #Python
python学习之编写查询ip程序
Feb 27 #Python
You might like
php下一个阿拉伯数字转中文数字的函数
2007/07/16 PHP
网友原创的PHP模板类代码
2008/09/07 PHP
php处理斐波那契数列非递归方法
2012/02/04 PHP
PHP中Header使用的HTTP协议及常用方法小结
2014/11/04 PHP
PHP进程同步代码实例
2015/02/12 PHP
基于ThinkPHP5.0实现图片上传插件
2017/09/25 PHP
使用PHPWord生成word文档的方法详解
2019/06/06 PHP
php遍历目录下文件并按修改时间排序操作示例
2019/07/12 PHP
firefox浏览器下javascript 拖动层效果与原理分析代码
2007/12/04 Javascript
jQuery右键菜单contextMenu使用实例
2011/09/28 Javascript
Javascript模块化编程(一)模块的写法最佳实践
2013/01/17 Javascript
自己封装的常用javascript函数分享
2015/01/07 Javascript
js实现类似jquery里animate动画效果的方法
2015/04/10 Javascript
AngularJs 弹出模态框(model)
2016/04/07 Javascript
javascript insertAfter()定义与用法示例
2016/07/25 Javascript
html+js+highcharts绘制圆饼图表的简单实例
2016/08/04 Javascript
用node和express连接mysql实现登录注册的实现代码
2017/07/05 Javascript
AngularJS中使用three.js的实例详解
2017/07/21 Javascript
React 高阶组件入门介绍
2018/01/11 Javascript
加快Vue项目的开发速度的方法
2018/12/12 Javascript
JS简单数组排序操作示例【sort方法】
2019/05/17 Javascript
2019年度web前端面试题总结(主要为Vue面试题)
2020/01/12 Javascript
[03:42]2014DOTA2西雅图国际邀请赛7月9日TOPPLAY
2014/07/09 DOTA
[01:38]完美世界高校联赛决赛花絮
2018/12/02 DOTA
python实现求特征选择的信息增益
2018/12/18 Python
pycharm 将python文件打包为exe格式的方法
2019/01/16 Python
python 批量修改 labelImg 生成的xml文件的方法
2019/09/09 Python
django model通过字典更新数据实例
2020/04/01 Python
Selenium执行完毕未关闭chromedriver/geckodriver进程的解决办法(java版+python版)
2020/12/07 Python
Guess欧洲官网:美国服饰品牌
2019/08/06 全球购物
英国水族馆和池塘用品购物网站:Warehouse Aquatics
2019/08/29 全球购物
安全检查验收制度
2014/01/12 职场文书
家庭困难证明
2014/10/12 职场文书
80后创业总结的9条职场用人思想,记得收藏
2019/08/13 职场文书
CSS控制继承中的height能变为可继承吗
2022/06/10 HTML / CSS
windows10声卡驱动怎么安装?win10声卡驱动安装操作步骤教程
2022/08/05 数码科技