Python练手项目0010
2017-01-11 13:02
344 查看
本项目采用的是https://github.com/Yixiaohan/show-me-the-code中所提供的练习项目,所有代码均为原创,转载请注明,谢谢。
问题描述:使用 Python 生成类似于下图中的字母验证码图片
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 12:48:02 2017
@author: sky
"""
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import string
IMAGE_MODE = 'RGB'
IMAGE_BG_COLOR = (255,255,255)
Image_Font = 'arial.ttf'
chars = string.letters + string.digits
text = ''.join(random.sample(chars,10))
def colorRandom():
return (random.randint(32,127),random.randint(32,127),random.randint(32,127))
#change 噪点频率(%)
def create_identifying_code(strs, width=1080, height=800, chance=2):
im = Image.new(IMAGE_MODE, (width, height), IMAGE_BG_COLOR)
draw = ImageDraw.Draw(im)
#绘制背景噪点
for w in xrange(width):
for h in xrange(height):
if chance < random.randint(1, 100):
draw.point((w, h), fill=colorRandom())
font = ImageFont.truetype(Image_Font, 100)
font_width, font_height = font.getsize(strs)
strs_len = len(strs)
x = (width - font_width)/2
y = (height - font_height)/2
#逐个绘制文字
for i in strs:
draw.text((x,y), i, colorRandom(), font)
x += font_width/strs_len
#模糊
im = im.filter(ImageFilter.BLUR)
im.save('identifying_code_pic.jpg')
if __name__ == '__main__':
create_identifying_code(text)
详细代码和结果,可以参考https://github.com/g8015108/exercise-for-python
问题描述:使用 Python 生成类似于下图中的字母验证码图片
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 12:48:02 2017
@author: sky
"""
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import string
IMAGE_MODE = 'RGB'
IMAGE_BG_COLOR = (255,255,255)
Image_Font = 'arial.ttf'
chars = string.letters + string.digits
text = ''.join(random.sample(chars,10))
def colorRandom():
return (random.randint(32,127),random.randint(32,127),random.randint(32,127))
#change 噪点频率(%)
def create_identifying_code(strs, width=1080, height=800, chance=2):
im = Image.new(IMAGE_MODE, (width, height), IMAGE_BG_COLOR)
draw = ImageDraw.Draw(im)
#绘制背景噪点
for w in xrange(width):
for h in xrange(height):
if chance < random.randint(1, 100):
draw.point((w, h), fill=colorRandom())
font = ImageFont.truetype(Image_Font, 100)
font_width, font_height = font.getsize(strs)
strs_len = len(strs)
x = (width - font_width)/2
y = (height - font_height)/2
#逐个绘制文字
for i in strs:
draw.text((x,y), i, colorRandom(), font)
x += font_width/strs_len
#模糊
im = im.filter(ImageFilter.BLUR)
im.save('identifying_code_pic.jpg')
if __name__ == '__main__':
create_identifying_code(text)
详细代码和结果,可以参考https://github.com/g8015108/exercise-for-python
相关文章推荐
- python练手项目(1)——字符图片生成
- Python练手项目0016
- 70个Python练手项目列表(都有完整教程)
- 有哪些适合新手练手的Python项目?
- 【Python】 Flask 缘分匹配练手项目
- Python练手项目0 - 给头像右上角添加数字
- Python练手项目0014
- Python练手项目
- Python学习路径及练手项目合集
- python练手项目
- Python练手项目0006
- python练手项目0005
- Python练手项目0015
- 有哪些适合新手练手的Python项目?
- Python练手项目(2)——200行实现2048小游戏
- Python之路【第二十四篇】:Python学习路径及练手项目合集
- python练手项目0007
- 利用Caffe+Python实现Kaggle上Digit Recognition练手项目
- 10个Python练手项目