Kaptcha是开源的图形验证码,相关的介绍文章已经不少了,本文讲述如何利用Kaptcha实现图形验证码的云函数全过程,阅读本文的先决条件是你已经熟悉了Kaptcha的使用方法,并且了解了腾讯Serverless产品SCF的基本操作。
云函数是单例模式运行的,所以使用第三方依赖的时候,要对第三方的对象实例化, Java 的一些web框架通过配置实现了第三方对象的实例化,所以业务代码只需要遵循框架约束直接使用即可,而云函数需要自己实例化这些第三方对象,一般情况下在云函数的构造函数部分实例化,这样在云函数本身对象实例化的时候就初始化了这些第三方组件。
云函数工程结构
本工程包含了工程package和resources,其中resources中放置一些配置文件,本工程是Kaptcha的配置属性。
云函数构造函数
构造函数里边实现了对Kaptcha组件的初始化,具体过程为:
- 读取配置文件的属性
- 实例化配置对象 Config
- 实例化Kaptcha对象作为云函数内部私有对象
private DefaultKaptcha kaptchaProducer;
public Mainhandler() {
Properties properties=new Properties();
FileInputStream in = null;
try {
in = new FileInputStream("kaptcha.properties");
properties.load(in);
in.close();
Config config=new Config(properties);
kaptchaProducer=new DefaultKaptcha();
kaptchaProducer.setConfig(config);
} catch (FileNotFoundException e) {
System.out.println(e.getLocalizedMessage());
} catch (IOException e) {
System.out.println(e.getLocalizedMessage());
}
}
kaptcha. border =yes
kaptcha.border.color=105,179,90
kaptcha.textproducer.font.color=blue
kaptcha.image.width=120
kaptcha.image.height=50
kaptcha.textproducer.font.size=27
kaptcha.session.key=code
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.names=Arial,Courier
kaptcha.textproducer.char.string=0123456789abcdefghijklmnopqrstuvwxyz
kaptcha.obscurificator.impl= com .google.code.kaptcha.impl.WaterRipple
kaptcha.noise.color= black
kaptcha.noise.impl=com.google.code.kaptcha.impl.DefaultNoise
kaptcha.background.clear.from=185,56,213
kaptcha.background.clear.to=white
kaptcha.textproducer.char.space=3
Kaptcha配置文件kaptcha.properties
生成图形验证码函数
利用Kaptcha生成图形验证码的方法和Java其他Web类框架没有区别,就不赘述,直接上代码
public Map<String,String> generateCode(APIGatewayProxyRequestEvent event, Context context){
String capText = kaptchaProducer.createText();
Map<String, String> value = new HashMap<>();
BufferedImage bi = kaptchaProducer.createImage(capText);
ByteArray outputStream outputStream = new ByteArrayOutputStream();
try {
ImageIO.write(bi, "jpg", outputStream);
String base64Img = Base64.getEncoder().encodeToString(outputStream.toByteArray());
value.put("capText", capText);
value.put("image", base64Img);
} catch (IOException e) {
System.out.println(e.getLocalizedMessage());
}
return value;
}
部署云函数到腾讯的SCF