python 利用 PIL 生成随机验证码图片【附:使用DOS命令更换pip下载源】

本是古典 何须时尚 2023-10-01 12:36 62阅读 0赞

声明:PIL资料来自博客园,详细资料请点击 https://www.cnblogs.com/fu-yong/p/8811851.html

一、验证码图片样式:
在这里插入图片描述
二、模块

  • PIL (需要安装,使用命令: pip install pillow)
  • random

三、代码
更换路径后可以直接使用

  1. from PIL import Image,ImageFont,ImageDraw
  2. import random
  3. #用于生成随机的颜色值的函数
  4. def getRandomColor():
  5. c1 = random.randint(0,255)
  6. c2 = random.randint(0,255)
  7. c3 = random.randint(0,255)
  8. return (c1,c2,c3)
  9. #用于生成随机的字符串的函数
  10. def getRandomStr():
  11. random_num = str(random.randint(0,9)) #获取随机的数字0-9
  12. random_low_letter = chr(random.randint(97,122)) #获取随机的小写字母a-z
  13. random_upper_letter = chr(random.randint(65,90))#获取随机的大写字母A-Z
  14. #利用random,choice()方法获取三个值中的某一个
  15. random_char = random.choice([random_num,random_low_letter,random_upper_letter])
  16. return random_char
  17. #创建一个图片对象,参数是:RGB模式,图片宽高,颜色值
  18. image = Image.new('RGB',(150,30),getRandomColor())
  19. draw = ImageDraw.Draw(image) #获取一个画笔对象,传入创建的图片对象
  20. #创建一个图片字体对象,参数是:字体格式,字体大小
  21. #注:注意字体的安装目录,可以直接在python的安装目录下搜索:ttf
  22. font = ImageFont.truetype(r'C:\python\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\cmmi10.ttf',size=25)
  23. #循环5次写入字符到图片
  24. for i in range(5):
  25. random_char = getRandomStr()
  26. #在图片上写入得到的随机字符串,参数是:位置,字符串,颜色,字体格式
  27. draw.text((10 + i * 30,0),random_char,getRandomColor(),font=font)
  28. width = 150
  29. height = 30
  30. # 设置图片噪线
  31. for i in range(5):
  32. x1 = random.randint(0,width)
  33. x2 = random.randint(0,width)
  34. y1 = random.randint(0,height)
  35. y2 = random.randint(0,height)
  36. draw.line((x1,y1,x2,y2),fill=getRandomColor())
  37. # 设置图片噪点
  38. for i in range(5):
  39. draw.point([random.randint(0,width),random.randint(0,height)],fill=getRandomColor())
  40. x = random.randint(0,width)
  41. y = random.randint(0,height)
  42. draw.arc((x,y,x + 4,y + 4),0,90,fill=getRandomColor())
  43. #写入保存图片,参数是:open()函数传入对应的路径和图片名称,保存图片格式
  44. image.save(open(r'D:\Coding\randomCode.png','wb'),'png')

四、python pip更换下载源

1、部分国内常用下载源:
清华:https://pypi.tuna.tsinghua.edu.cn/simple

阿里云:http://mirrors.aliyun.com/pypi/simple/

豆瓣:http://pypi.douban.com/simple/

2、使用下载源下载:
pip install -i 包名 http://pypi.douban.com/simple/

3、一劳永逸使用国内源下载:

pip config set global.index-url 国内镜像地址
如:
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

发表评论

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

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

相关阅读