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模仿POST提交HTTP数据及使用Cookie值的方法
Nov 10 Python
python中xrange用法分析
Apr 15 Python
python使用WMI检测windows系统信息、硬盘信息、网卡信息的方法
May 15 Python
Python实时获取cmd的输出
Dec 13 Python
Python 爬虫的工具列表大全
Jan 31 Python
Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS浅析
May 08 Python
python实现趣味图片字符化
Apr 30 Python
pytorch构建多模型实例
Jan 15 Python
python GUI库图形界面开发之PyQt5下拉列表框控件QComboBox详细使用方法与实例
Feb 27 Python
TensorFlow2.0使用keras训练模型的实现
Feb 20 Python
Python爬取用户观影数据并分析用户与电影之间的隐藏信息!
Jun 29 Python
Pyhton爬虫知识之正则表达式详解
Apr 01 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
MAC下通过改apache配置文件切换php多版本的方法
2017/04/26 PHP
javascript日期转换 时间戳转日期格式
2011/11/05 Javascript
JS判定是否原生方法
2013/07/22 Javascript
微信小程序 自己制作小组件实例详解
2016/12/22 Javascript
Javascript 详解封装from表单数据为json串进行ajax提交
2017/03/29 Javascript
微信小程序支付及退款流程详解
2017/11/30 Javascript
修改node.js默认的npm安装目录实例
2018/05/15 Javascript
微信小程序 slot踩坑的解决
2019/04/01 Javascript
js实现转动骰子模型
2019/10/24 Javascript
详解vue 组件
2020/06/11 Javascript
[02:16]DOTA2超级联赛专访Burning 逆袭需要抓住机会
2013/06/24 DOTA
[51:14]LGD vs VP 2018国际邀请赛淘汰赛BO3 第一场 8.21
2018/08/22 DOTA
Python实现的监测服务器硬盘使用率脚本分享
2014/11/07 Python
Python中的sort()方法使用基础教程
2017/01/08 Python
利用Python中的pandas库对cdn日志进行分析详解
2017/03/07 Python
Python基于csv模块实现读取与写入csv数据的方法
2018/01/18 Python
对python函数签名的方法详解
2019/01/22 Python
Python lambda表达式filter、map、reduce函数用法解析
2019/09/11 Python
python多线程高级锁condition简单用法示例
2019/11/07 Python
Python批量启动多线程代码实例
2020/02/18 Python
python 弧度与角度互转实例
2020/04/15 Python
python 读txt文件,按‘,’分割每行数据操作
2020/07/05 Python
Python实现简单猜数字游戏
2021/02/03 Python
骆驼官方商城:CAMEL
2016/11/22 全球购物
IRO美国官网:法国服装品牌
2018/03/06 全球购物
英国莱斯特松木橡木家具网上商店:Choice Furniture Superstore
2019/07/05 全球购物
什么是反射?如何实现反射?
2016/07/25 面试题
招商业务员岗位职责
2013/12/16 职场文书
党员思想汇报范文
2013/12/30 职场文书
保险专业大学生职业规划书
2014/03/03 职场文书
安全生产演讲稿
2014/05/09 职场文书
初中学习计划书范文
2014/09/15 职场文书
2014小学年度工作总结
2014/12/20 职场文书
毕业论文致谢信
2015/05/14 职场文书
南极大冒险观后感
2015/06/05 职场文书
教师节大会主持词
2015/07/06 职场文书