PIL简单操作,写一个好一点的验证码

骑猪看日落 2022-05-31 02:07 248阅读 0赞

前景

虽然说,在我的印象里面前几年用验证码图片较多,现在似乎都是用拼图或者短
信验证码的形式。但是我还是得学习一下如何写一个验证码图片:用的PIL模块

环境

  • python3
  • PIL模块

学习代码:

  1. from PIL import Image, ImageDraw, ImageFont, ImageFilter
  2. import random
  3. # 大写字母
  4. def rndChar():
  5. return chr(random.randint(65, 90))
  6. # 储存颜色的元组
  7. def rnd_color():
  8. color_tuple = ()
  9. for i in range(3):
  10. color_tuple += (random.randint(64, 255),)
  11. return color_tuple
  12. # 定义每一个字母的长宽w=60,h=60,一共四个字母4*60
  13. image = Image.new('RGB', (240, 60), 'white')
  14. # 字体对象
  15. font = ImageFont.truetype('FreeSans.ttf',36)
  16. # 创建Draw对象
  17. draw = ImageDraw.Draw(image)
  18. # 用点填充每个像素:
  19. for x in range(240):
  20. for y in range(60):
  21. draw.point((x,y), fill=rnd_color())
  22. # 输出文字:
  23. for t in range(4):
  24. draw.text((60 * t + 10, 10), rnd_char(), font=font, fill='blue')
  25. image.save('/home/dream/桌面/222.jpg')

这个是廖雪峰老师的代码,我先翻阅了pillow 的文档,查看了一下几个简单的模块方法,但是我觉得,平日里绘画图片,不是专门有工具嘛,应该用不到,所以我就浅浅的学习一下,为了以后的web登录界面的验证码打个小基础。PS:注意字体,ubuntu上好像老师的那个字体不能用,找不到。
这里写图片描述
这个验证码不大好,太简单了,于是我又重搞了一个验证码:

稍微改进一些

  1. from PIL import Image, ImageFont, ImageDraw, ImageFilter
  2. import random
  3. import string
  4. total = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345789'
  5. # 图片大小130 x 50
  6. width = 130
  7. heighth = 50
  8. # 先生成一个新图片对象
  9. im = Image.new('RGB',(width, heighth), 'white')
  10. # 设置字体
  11. font = ImageFont.truetype('FreeSans', 40)
  12. # 创建draw对象
  13. draw = ImageDraw.Draw(im)
  14. # 输出每一个文字
  15. for item in range(5):
  16. draw.text((5+random.randint(4,7)+20*item,5+random.randint(3,7)), text=random.choice(total), fill='black',font=font )
  17. # 划几根干扰线
  18. for num in range(8):
  19. x1 = random.randint(0, width/2)
  20. y1 = random.randint(0, heighth/2)
  21. x2 = random.randint(0, width)
  22. y2 = random.randint(heighth/2, heighth)
  23. draw.line(((x1, y1),(x2,y2)), fill='black', width=1)
  24. # 模糊下,加个帅帅的滤镜~
  25. im = im.filter(ImageFilter.FIND_EDGES)
  26. im.show()
  • 效果图:
    这里写图片描述
    是不是像一个比较正规点的验证码,其实就是增加了随机性,使得字符之间大概率会出现重影,增加了些破解难度

PS:今天在ubuntu上装了eclipse + pydev这个插件,当做一个IDE用。因为今天pycharm 的连接又出现麻烦了,认证服务器地址老是要换,万一哪天不行了,难不成就不用了?话说eclipse 里面写python 也挺好的。~

发表评论

表情:
评论列表 (有 0 条评论,248人围观)

还没有评论,来说两句吧...

相关阅读