生成base64格式的验证码
好奇看了一下公司的验证码是如何生成的,这里用到了EasyCaptcha(github地址:https://github.com/whvcse/EasyCaptcha),简单说一下如何使用以及具体的业务场景:
1、导入依赖:
maven:
<dependencies>
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
gradle:
dependencies {
compile 'com.github.whvcse:easy-captcha:1.6.2'
}
2、此处新建一个springboot项目用来测试:
controller:
package com.zym.testeasycaptcha.controller;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.UUID;
@Controller
public class TestController {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@RequestMapping("/test")
@ResponseBody
public String test(){
//EasyCaptcha为我们提供了png类型(SpecCaptcha),gif类型(GifCaptcha),
// 中文类型(ChineseCaptcha),中文gif类型(ChineseGifCaptcha) ,算术类型(ArithmeticCaptcha),此处我们用算术类型测试
ArithmeticCaptcha captcha = new ArithmeticCaptcha(130,48); //宽度、长度
//几位数运算
captcha.setLen(3);
//获取生成的文本
String result =captcha.text();
//生成一个uuid用来保存到redis中
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
String key = uuid.toString();
redisTemplate.opsForValue().set(key,result);
//将图片返回给前端,只需要base64格式
System.out.println(captcha.toBase64());
return captcha.toBase64();
}
}
启动项目,调用该接口,后台输出:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIIAAAAwCAIAAABSYzXUAAAL1UlEQVR42u1aC0xUVxp211jXuMY125jGNF1jsnGbxpgNUatBrVofjVGzPmJpjMGqExABBaqC4oIWlwqFpZQK8nBEIoKOinQWDUUEEa3yLC95I+UhD3kJRR7D2e+fc7l3ZO7wmDGb7u79c3Jzzrln5t77f+f//+//753EFPkVyCRFBQoMiigwKDAoosCgwK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XI9m2pKwEdpRjbU21vJQUkwx3WJBsS1Umo7NmvxYtK2OvXo3jJSi0DOUmVdKWXxgpZMuBj8k1gb8iMBS1UIhGh8MA07FEbL3U3Bo8Qm6MuRhUapzuS1aqvby4NdQZs0UjawCVes19NTXRHrZMCgupooeocOwYlTcM2LIRDKUvqIgNdoQOfyd6JpPqS0ik4Z169HxSLDetvmzp2zdeszMur85adWjT4W8RORLS8kQWCw+GZva1eM3OuLyau2pV+eHDiBztPj6669dFD4Ym/TgpSSiNWiA8KsAjcu/k6zvqJwFIlUGQgIRYWxUF0fuTOAGDBRHy76snVm7TDb29xsVUudu4bXEJseRieWvWmCp3G7cKbF2hYtxInIy/2rdAuPaR0MiSJZkPZMBNve7TG7fFanrlidANCxBfiILXHk19Y1/KwB2NE4MFO70r6yx6WQ93NE4MirZte1VXR6oHzQQG4ksDCyQgQHjjxgP1iIR9tM/FkMchMCB3Q4Nfii74P/h0DFm0Wi1m0eSLLLYDwSt20McADg5kFt7eI7/bUD6e/FWIAoMCgyIKDAoMiigwKDAoosCgwKCIAsN/hfwbBXEEFPovGigAAAAASUVORK5CYII=
我们可以在线转换一下,看一下长什么样子:
网址:http://tool.chinaz.com/tools/imgtobase/
效果:
看redis中保存的结果是否为4:
关于EasyCaptcha的简单测试就完成了