本篇文章主要介绍了Python简单的制作图片验证码实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这里示范的验证码都是简单的,你也可以把字符扭曲
Python第三方库无比强大,PIL 是python的一个d第三方图片处理模块,我们也可以使用它来生成图片验证码
PIL安装
命令安装:
pip install pillow
例子:生成图片,并填充文字
#!/usr/bin/python #-*-coding:utf-8-*- from PIL import Image, ImageDraw, ImageFont, ImageFilter # 实例一个图片对象240 x 60: width = 60 * 4 height = 60 # 图片颜色 clo = (43, 34, 88) # 我觉得是紫蓝色 image = Image.new('RGB', (width, height), clo) # 创建Font对象: # 字体文件可以使用操作系统的,也可以网上下载 font = ImageFont.truetype('./font/Arial.ttf', 36) # 创建Draw对象: draw = ImageDraw.Draw(image) # 输出文字: str1 = "ren ren Python" w = 4 #距离图片左边距离 h = 10 #距离图片上边距离 draw.text((w, h), str1, font=font) # 模糊: image.filter(ImageFilter.BLUR) code_name = 'test_code_img.jpg' save_dir = './{}'.format(code_name) image.save(save_dir, 'jpeg') print("已保存图片: {}".format(save_dir))
(venv) allenwoo@~/renren/code$ python test2.py 已保存图片: ./test_code_img.jpg
图片如下:
文字没有什么色彩,我们也可以加上颜色,只需要在 text 中传人 fill 参数就好
draw.text((w, h), str1, font=font, fill = (78, 64, 65))
随便加的颜色
我们还可以把背景弄成很多个小点,每隔n隔像素填充个其他颜色比如:
#!/usr/bin/python #-*-coding:utf-8-*- from PIL import Image, ImageDraw, ImageFont, ImageFilter # 实例一个图片对象240 x 60: width = 60 * 4 height = 60 # 图片颜色 clo = (43, 34, 88) # 我觉得是紫蓝色 image = Image.new('RGB', (width, height), clo) # 创建Font对象: # 字体文件可以使用操作系统的,也可以网上下载 font = ImageFont.truetype('./font/Arial.ttf', 36) # 创建Draw对象: draw = ImageDraw.Draw(image) # 填充像素: # 宽每隔 20, 高每隔5, 形成坐标x,y # 红色:220,20,60 for x in range(0, width, 20): for y in range(0, height, 5): draw.point((x, y), fill=(220, 20, 60)) # 输出文字: str1 = "we are renren" w = 4 #距离图片左边距离 h = 10 #距离图片上边距离 draw.text((w, h), str1, font=font, fill = (78, 64, 65)) # 模糊: image.filter(ImageFilter.BLUR) code_name = 'test_code_img.jpg' save_dir = './{}'.format(code_name) image.save(save_dir, 'jpeg') print("已保存图片: {}".format(save_dir))
结果图片:
PIL制作验证码
利用以上这些,还有我们之前学习的随机生成器random就可以做个验证码了,
生成验证码代码
#!/usr/bin/python #-*-coding:utf-8-*- from uuid import uuid1 from PIL import Image, ImageDraw, ImageFont, ImageFilter import random def rnd_char(): ''' 随机一个字母或者数字 :return: ''' # 随机一个字母或者数字 i = random.randint(1,3) if i == 1: # 随机个数字的十进制ASCII码 an = random.randint(97, 122) elif i == 2: # 随机个小写字母的十进制ASCII码 an = random.randint(65, 90) else: # 随机个大写字母的十进制ASCII码 an = random.randint(48, 57) # 根据Ascii码转成字符,return回去 return chr(an) # 干扰 def rnd_dis(): ''' 随机一个干扰字 :return: ''' d = ['^','-', '~', '_', '.'] i = random.randint(0, len(d)-1) return d[i] # 两个随机颜色都规定不同的区域,防止干扰字符和验证码字符颜色一样 # 随机颜色1: def rnd_color(): ''' 随机颜色,规定一定范围 :return: ''' return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)) # 随机颜色2: def rnd_color2(): ''' 随机颜色,规定一定范围 :return: ''' return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) def create_code(): # 240 x 60: width = 60 * 4 height = 60 image = Image.new('RGB', (width, height), (192, 192, 192)) # 创建Font对象: font = ImageFont.truetype('./font/Arial.ttf', 36) # 创建Draw对象: draw = ImageDraw.Draw(image) # 填充每个像素: for x in range(0, width, 20): for y in range(0, height, 10): draw.point((x, y), fill=rnd_color()) # 填充字符 _str = "" # 填入4个随机的数字或字母作为验证码 for t in range(4): c = rnd_char() _str = "{}{}".format(_str, c) # 随机距离图片上边高度,但至少距离30像素 h = random.randint(1, height-30) # 宽度的化,每个字符占图片宽度1/4,在加上10个像素空隙 w = width/4 * t + 10 draw.text((w, h), c, font=font, fill=rnd_color2()) # 实际项目中,会将验证码 保存在数据库,并加上时间字段 print("保存验证码 {} 到数据库".format(_str)) # 给图片加上字符干扰,密集度由 w, h控制 for j in range(0, width, 30): dis = rnd_dis() w = t * 15 + j # 随机距离图片上边高度,但至少距离30像素 h = random.randint(1, height - 30) draw.text((w, h), dis, font=font, fill=rndColor()) # 模糊: image.filter(ImageFilter.BLUR) # uuid1 生成唯一的字符串作为验证码图片名称 code_name = '{}.jpg'.format(uuid1()) save_dir = './{}'.format(code_name) image.save(save_dir, 'jpeg') print("已保存图片: {}".format(save_dir)) # 当直接运行文件的是和,运行下面代码 if name == "main": create_code()
(venv) allenwoo@~/renren/code$ python test.py 保存验证码 ef3k 到数据库 已保存图片: ./c86e03c0-1c23-11e7-999d-f45c89c09e61.jpg (venv) allenwoo@~/renren/code$ python test.py 保存验证码 I37X 到数据库 已保存图片: ./cb8aed02-1c23-11e7-9b18-f45c89c09e61.jpg (venv) allenwoo@~/renren/code$ python test.py 保存验证码 vVL1 到数据库 已保存图片: ./cc120da8-1c23-11e7-b762-f45c89c09e61.jpg (venv) allenwoo@~/renren/code$ python test.py 保存验证码 K6w3 到数据库 已保存图片: ./cc891e05-1c23-11e7-b7ec-f45c89c09e61.jpg
你觉得难不难呢?最后这个生成验证码代码中有些逻辑问题要理解下
以上是Python如何制作图片验证码的简单实例的详细内容。更多信息请关注PHP中文网其他相关文章!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

toAccesselementsInapythonlist,useIndIndexing,负索引,切片,口头化。1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

Atom编辑器mac版下载
最流行的的开源编辑器

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中