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脚本自动生成需要文件实例代码
Feb 04 Python
用 Python 爬了爬自己的微信朋友(实例讲解)
Aug 25 Python
利用Python yagmail三行代码实现发送邮件
May 11 Python
解决python中无法自动补全代码的问题
Dec 04 Python
Python 限制线程的最大数量的方法(Semaphore)
Feb 22 Python
解决pyinstaller打包发布后的exe文件打开控制台闪退的问题
Jun 21 Python
Python 旋转打印各种矩形的方法
Jul 09 Python
解决Python中pandas读取*.csv文件出现编码问题
Jul 12 Python
Python3进制之间的转换代码实例
Aug 24 Python
Python 多线程其他属性以及继承Thread类详解
Aug 28 Python
pytorch 中pad函数toch.nn.functional.pad()的用法
Jan 08 Python
pygame用blit()实现动画效果的示例代码
May 28 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
星际争霸兵种名称对照表
2020/03/04 星际争霸
Windows Apache2.2.11及Php5.2.9-1的安装与配置方法
2009/06/08 PHP
php根据身份证号码计算年龄的实例代码
2014/01/18 PHP
PHP图像处理之使用imagecolorallocate()函数设置颜色例子
2014/11/19 PHP
php递归遍历多维数组的方法
2015/04/18 PHP
如何使用Gitblog和Markdown建自己的博客
2015/07/31 PHP
Win7环境下Apache连接MySQL提示连接已重置的解决办法
2017/05/09 PHP
PHP单例模式应用示例【多次连接数据库只实例化一次】
2018/12/18 PHP
laravel框架使用阿里云短信发送消息操作示例
2020/02/15 PHP
JavaScript整除运算函数ceil和floor的区别分析
2015/04/14 Javascript
jquery插件EasyUI中form表单提交实例分享
2016/01/11 Javascript
JavaScript学习笔记之创建对象
2016/03/25 Javascript
Angular 4 指令快速入门教程
2017/06/07 Javascript
Element-UI中Upload上传文件前端缓存处理示例
2019/02/21 Javascript
基于JS实现计算24点算法代码实例解析
2020/07/23 Javascript
prettier自动格式化去换行的实现代码
2020/08/25 Javascript
Python读取文件内容的三种常用方式及效率比较
2017/10/07 Python
在Python程序员面试中被问的最多的10道题
2017/12/05 Python
Windows环境下python环境安装使用图文教程
2018/03/13 Python
Python数据持久化shelve模块用法分析
2018/06/29 Python
对TensorFlow中的variables_to_restore函数详解
2018/07/30 Python
python字符串分割及字符串的一些常规方法
2019/07/24 Python
tensorflow 变长序列存储实例
2020/01/20 Python
python 爬取马蜂窝景点翻页文字评论的实现
2020/01/20 Python
Python标准库:内置函数max(iterable, *[, key, default])说明
2020/04/25 Python
python json.dumps() json.dump()的区别详解
2020/07/14 Python
Python把图片转化为pdf代码实例
2020/07/28 Python
pytorch学习教程之自定义数据集
2020/11/10 Python
python中四舍五入的正确打开方式
2021/01/18 Python
工作作风承诺书
2014/08/30 职场文书
2014广电局实施党的群众路线教育实践活动方案思想汇报
2014/09/22 职场文书
JS数组的常用方法整理
2021/03/31 Javascript
python 爬取豆瓣网页的示例
2021/04/13 Python
pytorch损失反向传播后梯度为none的问题
2021/05/12 Python
排查MySQL生产环境索引没有效果
2022/04/11 MySQL
Go Grpc Gateway兼容HTTP协议文档自动生成网关
2022/06/16 Golang