PIL简单操作,写一个好一点的验证码
前景
虽然说,在我的印象里面前几年用验证码图片较多,现在似乎都是用拼图或者短
信验证码的形式。但是我还是得学习一下如何写一个验证码图片:用的PIL模块
环境
- python3
- PIL模块
学习代码:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 大写字母
def rndChar():
return chr(random.randint(65, 90))
# 储存颜色的元组
def rnd_color():
color_tuple = ()
for i in range(3):
color_tuple += (random.randint(64, 255),)
return color_tuple
# 定义每一个字母的长宽w=60,h=60,一共四个字母4*60
image = Image.new('RGB', (240, 60), 'white')
# 字体对象
font = ImageFont.truetype('FreeSans.ttf',36)
# 创建Draw对象
draw = ImageDraw.Draw(image)
# 用点填充每个像素:
for x in range(240):
for y in range(60):
draw.point((x,y), fill=rnd_color())
# 输出文字:
for t in range(4):
draw.text((60 * t + 10, 10), rnd_char(), font=font, fill='blue')
image.save('/home/dream/桌面/222.jpg')
这个是廖雪峰老师的代码,我先翻阅了pillow 的文档,查看了一下几个简单的模块方法,但是我觉得,平日里绘画图片,不是专门有工具嘛,应该用不到,所以我就浅浅的学习一下,为了以后的web登录界面的验证码打个小基础。PS:注意字体,ubuntu上好像老师的那个字体不能用,找不到。
这个验证码不大好,太简单了,于是我又重搞了一个验证码:
稍微改进一些
from PIL import Image, ImageFont, ImageDraw, ImageFilter
import random
import string
total = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345789'
# 图片大小130 x 50
width = 130
heighth = 50
# 先生成一个新图片对象
im = Image.new('RGB',(width, heighth), 'white')
# 设置字体
font = ImageFont.truetype('FreeSans', 40)
# 创建draw对象
draw = ImageDraw.Draw(im)
# 输出每一个文字
for item in range(5):
draw.text((5+random.randint(4,7)+20*item,5+random.randint(3,7)), text=random.choice(total), fill='black',font=font )
# 划几根干扰线
for num in range(8):
x1 = random.randint(0, width/2)
y1 = random.randint(0, heighth/2)
x2 = random.randint(0, width)
y2 = random.randint(heighth/2, heighth)
draw.line(((x1, y1),(x2,y2)), fill='black', width=1)
# 模糊下,加个帅帅的滤镜~
im = im.filter(ImageFilter.FIND_EDGES)
im.show()
- 效果图:
是不是像一个比较正规点的验证码,其实就是增加了随机性,使得字符之间大概率会出现重影,增加了些破解难度
PS:今天在ubuntu上装了eclipse + pydev这个插件,当做一个IDE用。因为今天pycharm 的连接又出现麻烦了,认证服务器地址老是要换,万一哪天不行了,难不成就不用了?话说eclipse 里面写python 也挺好的。~
还没有评论,来说两句吧...