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

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

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

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

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

from PIL import Image,ImageFont,ImageDraw
import random
#用于生成随机的颜色值的函数
def getRandomColor():
  c1 = random.randint(0,255)
  c2 = random.randint(0,255)
  c3 = random.randint(0,255)
  return (c1,c2,c3)
#用于生成随机的字符串的函数
def getRandomStr():
  random_num = str(random.randint(0,9)) #获取随机的数字0-9
  random_low_letter = chr(random.randint(97,122)) #获取随机的小写字母a-z
  random_upper_letter = chr(random.randint(65,90))#获取随机的大写字母A-Z
  #利用random,choice()方法获取三个值中的某一个
  random_char = random.choice([random_num,random_low_letter,random_upper_letter]) 
  return random_char
 #创建一个图片对象,参数是:RGB模式,图片宽高,颜色值
image = Image.new('RGB',(150,30),getRandomColor())
draw = ImageDraw.Draw(image) #获取一个画笔对象,传入创建的图片对象
 #创建一个图片字体对象,参数是:字体格式,字体大小
 #注:注意字体的安装目录,可以直接在python的安装目录下搜索:ttf
font = ImageFont.truetype(r'C:\python\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\cmmi10.ttf',size=25)
#循环5次写入字符到图片
for i in range(5):
  random_char = getRandomStr()
  #在图片上写入得到的随机字符串,参数是:位置,字符串,颜色,字体格式
  draw.text((10 + i * 30,0),random_char,getRandomColor(),font=font)

width = 150
height = 30
# 设置图片噪线
for i in range(5):
  x1 = random.randint(0,width)
  x2 = random.randint(0,width)
  y1 = random.randint(0,height)
  y2 = random.randint(0,height)
  draw.line((x1,y1,x2,y2),fill=getRandomColor())
# 设置图片噪点
for i in range(5):
  draw.point([random.randint(0,width),random.randint(0,height)],fill=getRandomColor())
  x = random.randint(0,width)
  y = random.randint(0,height)
  draw.arc((x,y,x + 4,y + 4),0,90,fill=getRandomColor())
  #写入保存图片,参数是:open()函数传入对应的路径和图片名称,保存图片格式
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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

讷言丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值