Python 生成验证码图片
477 views
0
上网找了半天,找到一个PyCAPTCHA可以用(需要安装pil)。代码是生成中文的验证图,
需要在Captcha\data\fonts目录里面建一个子目录cn再copy一个中文字体进去就可以了,
我copy的是幼园(simyou.ttf)。如果是英文验证码的话,用自代的字体就可以了。
代码里面把FontFactory的参数改一下就可以
# -*- coding: utf-8 -*-
from Captcha.Visual import Text, Backgrounds, Distortions, ImageCaptcha
from Captcha import Words
class cnfont_create(ImageCaptcha):
"""A fixed-solution CAPTCHA that can be used to hide email addresses or URLs from bots"""
fontFactory = Text.FontFactory(30, "cn/simyou.ttf")
defaultSize = (150,40)
def getLayers(self, solution=u'测试'):
self.addSolution(solution)
textLayer = Text.TextLayer(solution,
borderSize = 2,
fontFactory = self.fontFactory)
return [
Backgrounds.CroppedImage(),
textLayer,
Distortions.SineWarp(amplitudeRange = (4, 4)),
]
g = cnfont_create()
i = g.render()
i.save("output.png")
python生成验证码,文字转换为图片
在58或者赶集等一些网站上经常看到手机号是图片格式,或者一些网站的验证码。这些都是动态生成的,今天我们来看一下如何用python把文字生成图片。其实今天主要借助pygame的图像渲染模块,这样比较简单,顺便帮大家复习下pygame这个游戏框架。好啦,直接上代码吧。
环境:python2.7,装有python3的同学也可以测试一下
#coding: UTF-8
#载入必要的模块
import os
import pygame
from pygame.locals import *
#pygame初始化
pygame.init()
text = u"PythonTab中文网"
#设置字体和字号
font = pygame.font.SysFont('Microsoft YaHei', 64)
#渲染图片,设置背景颜色和字体样式,前面的颜色是字体颜色
ftext = font.render(text, True, (65, 83, 130),(255, 255, 255))
#保存图片
pygame.image.save(ftext, "D:/pythontab.jpg")#图片保存地址
注意:如果要生成中文其中的字体设置中,要设置支持中文的字体。不然会生成乱码
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2015-07-24 02:00:03
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!
转载注明: Python 生成验证码图片 (米扑博客)