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 基本数据类型占用内存空间大小的实例
Jun 12 Python
Python中pandas dataframe删除一行或一列:drop函数详解
Jul 03 Python
python 平衡二叉树实现代码示例
Jul 07 Python
python实现三维拟合的方法
Dec 29 Python
Python文件操作中进行字符串替换的方法(保存到新文件/当前文件)
Jun 28 Python
使用django的ORM框架按月统计近一年内的数据方法
Jul 18 Python
详解Python中的分支和循环结构
Feb 11 Python
python使用正则表达式去除中文文本多余空格,保留英文之间空格方法详解
Feb 11 Python
如何理解python对象
Jun 21 Python
如何让python的运行速度得到提升
Jul 08 Python
python用tkinter开发的扫雷游戏
Jun 01 Python
解析目标检测之IoU
Jun 26 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
phpinfo 系统查看参数函数代码
2009/06/05 PHP
PHP curl模拟浏览器采集阿里巴巴的实现代码
2011/04/20 PHP
php设计模式 FlyWeight (享元模式)
2011/06/26 PHP
解析使用substr截取UTF-8中文字符串出现乱码的问题
2013/06/20 PHP
Thinkphp 空操作、空控制器、命名空间(详解)
2017/05/05 PHP
js字符串的各种格式的转换 ToString,Format
2011/08/08 Javascript
屏蔽script注入小例子
2013/11/12 Javascript
Js与下拉列表处理问题解决
2014/02/13 Javascript
PHP+MySQL+jQuery随意拖动层并即时保存拖动位置实例讲解
2015/10/09 Javascript
TypeOf这些知识点你了解吗
2016/02/21 Javascript
PHP获取当前页面完整URL的方法
2016/12/02 Javascript
简单实现JS倒计时效果
2016/12/23 Javascript
ionic2 tabs使用 Modal底部tab弹出框
2016/12/30 Javascript
socket.io与pm2(cluster)集群搭配的解决方案
2017/06/02 Javascript
理解 Node.js 事件驱动机制的原理
2017/08/16 Javascript
封装运动框架实战左右与上下滑动的焦点轮播图(实例)
2017/10/17 Javascript
Vue单页面应用中实现Markdown渲染
2021/02/14 Vue.js
[53:52]OG vs EG 2018国际邀请赛淘汰赛BO3 第二场 8.23
2018/08/24 DOTA
python使用三角迭代计算圆周率PI的方法
2015/03/20 Python
简单了解python高阶函数map/reduce
2019/06/28 Python
Pyorch之numpy与torch之间相互转换方式
2019/12/31 Python
Python使用type动态创建类操作示例
2020/02/29 Python
python pyecharts 实现一个文件绘制多张图
2020/05/13 Python
PySide2出现“ImportError: DLL load failed: 找不到指定的模块”的问题及解决方法
2020/06/10 Python
python中二分查找法的实现方法
2020/12/06 Python
德国大型的家具商店:Pharao24.de
2016/10/02 全球购物
初婚未育证明
2014/01/15 职场文书
知名企业招聘广告词大全
2014/03/18 职场文书
开业主持词
2014/03/21 职场文书
元旦晚会活动总结
2014/07/09 职场文书
地震捐款倡议书
2014/08/29 职场文书
2015年审计人员工作总结
2015/05/26 职场文书
汽车修理厂管理制度
2015/08/05 职场文书
2016年“世界环境日”校园广播稿
2015/12/18 职场文书
Ajax实现局部刷新的方法实例
2021/03/31 Javascript
JavaScript实现栈结构详细过程
2021/12/06 Javascript