Base64生成验证码
通过工具类生成key和图片验证码
public class VerifyUtil {
private static final char[] chars = {
'1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
private static final int SIZE = 4;
private static final int LINES = 4;
private static final int WIDTH = 83;
private static final int HEIGHT = 40;
private static final int FONT_SIZE = 30;
private static int[] w = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
public static Object[] createImage() {
StringBuffer sb = new StringBuffer();
BufferedImage image = new BufferedImage(
WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.setColor(Color.LIGHT_GRAY);
graphic.fillRect(0, 0, WIDTH, HEIGHT);
Random ran = new Random();
for (int i = 0; i <SIZE; i++) {
int n = ran.nextInt(chars.length);
graphic.setColor(getRandomColor());
graphic.setFont(new Font(
null, Font.BOLD + Font.ITALIC, FONT_SIZE));
graphic.drawString(
chars[n] + "", i * WIDTH / SIZE, HEIGHT*2/3);
sb.append(chars[n]);
}
for (int i = 0; i < LINES; i++) {
graphic.setColor(getRandomColor());
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
return new Object[]{sb.toString(), image};
}
public static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256),
ran.nextInt(256), ran.nextInt(256));
return color;
}
}
对图片验证码进行Base64编码
@RequestMapping("/face/getverifycode")
@ResponseBody
public Object getVerifyCode() {
RequestResult requestResult = new RequestResult();
requestResult.setCode(ResultTypeEnum.FU_SUCCESS_0000.getCode());
requestResult.setMessage(ResultTypeEnum.FU_SUCCESS_0000.getDesc());
Map dataMap = new HashMap(4);
ByteArrayOutputStream outputStream = null;
try {
Object[] objects = VerifyUtil.createImage();
BufferedImage image = (BufferedImage) objects[1];
String valueCode = objects[0].toString().toLowerCase();
String key = UUID.randomUUID().toString();
redisUtil.set(key, valueCode, 1, TimeUnit.MINUTES);
outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outputStream);
String pic = Base64.getEncoder().encodeToString(outputStream.toByteArray());
dataMap.put("codekey", key);
dataMap.put("codepic", pic);
requestResult.setData(dataMap);
} catch (Exception e) {
log.error("生成验证码错误", e);
requestResult.setCode(ResultTypeEnum.FU_EXC_9702.getCode());
requestResult.setMessage(ResultTypeEnum.FU_EXC_9702.getDesc());
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ex) {
log.error("关闭流错误", ex);
}
}
return requestResult;
}
前端页面调用方法
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
<meta name="viewport"
content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,initial-scale=1.0,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<meta name="format-detection" content="email=no">
<title></title>
// 这个地方我使用的是thymeleaf,所以引入资源文件不一样,各位可以根据实际情况进行替换
<link rel="stylesheet" th:href="@{/css/common.css}"/>
<script type="text/javascript" th:src="@{/js/jquery-2.1.4.min.js}"></script>
<script th:inline="javascript">
$(function(){
refreshimg();
});
function refreshimg () {
$.ajax({
type : "post",
dataType : "json",
url : "/face/getverifycode",
data : {},
success : function(data){
if (data.data) {
$('#randomImage').attr('src', 'data:image/png;base64,'+ data.data.codepic);
$("#codekey").val(data.data.codekey);
}
},
error : function(){
console.log("生成验证码错误!");
}
});
}
</script>
<style>
.inputCodeClass {
flex: 1;
height: 1.6rem;
line-height: 1.6rem;
font-size: 1.4rem;
width: 6rem;
text-align: right;
margin: 0 0.4rem;
color: red;
border: none;
outline: none;
font-weight: bold;
}
</style>
</head>
<body>
<section class="withdrawResult">
<article class="protocol_content">
<div style="padding-top: 20px;display: flex;">
<p>
<span>验证码:</span>
<input class="inputCodeClass" type="text" id="inputCode" name="inputCode" style="text-align: left;border: 1px solid #686868"/>
<input type="hidden" id="codekey" name="codekey" value=""/>
</p>
<img id="randomImage" title="点击更换" onclick="javascript:refreshimg()" src=""/>
</div>
</article>
</section>
</body>
</html>