java隨機圖片驗證碼
阿新 • • 發佈:2021-07-18
1. 驗證碼工具類
import java.awt.*; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.Random; public class VerifyUtil { // 驗證碼字符集 private static final char[] CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; // 字元數量 private static final int SIZE = 6; // 干擾線數量 private static final int LINES = 5; // 寬度 private static final int WIDTH = 120; // 高度 private static final int HEIGHT = 40; // 字型大小 private static final int FONT_SIZE = 30; /** * 生成隨機驗證碼及圖片 */ public static Map<String, Object> createImage() { StringBuffer sb = new StringBuffer(); // 1.建立空白圖片 BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); // 2.獲取圖片畫筆 Graphics graphic = image.getGraphics(); // 3.設定畫筆顏色 graphic.setColor(Color.LIGHT_GRAY); // 4.繪製矩形背景 graphic.fillRect(0, 0, WIDTH, HEIGHT); // 5.畫隨機字元 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]); } // 6.畫干擾線 for (int i = 0; i < LINES; i++) { // 設定隨機顏色 graphic.setColor(getRandomColor()); // 隨機畫線 graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), ran.nextInt(WIDTH), ran.nextInt(HEIGHT)); } // 7.返回驗證碼和圖片 Map<String, Object> map = new HashMap<>(); //驗證碼 map.put("code", sb.toString()); //圖片 map.put("image", image); return map; } /** * 隨機取色 */ public static Color getRandomColor() { Random ran = new Random(); return new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256)); } }
2. redis工具類
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; public class MyJedisUtils { public static final String HOST = "127.0.0.1"; public static final Integer POST = 6379; public static JedisPool jedisPool; /** * 獲取 redis 預設連線 * @return */ public static Jedis getJedis(){ jedisPool = new JedisPool(HOST,POST); return jedisPool.getResource(); } /** * 自定義獲取 redis 連線 * @param HOST * @param POST * @return */ public static Jedis getJedis(String HOST,Integer POST){ jedisPool = new JedisPool(HOST,POST); return jedisPool.getResource(); } /** * 關閉 redis 連線 * @param jedis */ public static void closeJedis(Jedis jedis){ if(jedis!=null&&jedis.isConnected()){ jedis.close(); } } }
3. 控制層類
import java.awt.*; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.Random; public class VerifyUtil { @GetMapping("code") @ResponseBody public Boolean code(String key_name, String code, HttpServletResponse response) throws IOException { // 獲取到的值 String key_value = null; // 獲取redis連線 Jedis jedis = MyJedisUtils.getJedis(); if(code==null){ Map<String, Object> map = VerifyUtil.createImage(); //將圖片輸出給瀏覽器 BufferedImage image = (BufferedImage) map.get("image"); response.setContentType("image/png"); OutputStream os = response.getOutputStream(); ImageIO.write(image, "png", os); // redis 設定 5 分鐘的存活時間 jedis.setex(key_name,300,map.get("code").toString()); return false; } key_value = jedis.get(key_name); // 關閉連線 MyJedisUtils.closeJedis(jedis); Boolean result = code.equals(key_value); if(result){ jedis.del(key_name); } return result; } }
4. 頁面程式碼
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登入</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- 引入樣式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- 引入元件庫 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<el-form :inline="true" :model="formInline" class="demo-form-inline">
<el-form-item label="驗證碼:">
<el-input v-model="formInline.code" placeholder="請輸入驗證碼"></el-input>
</el-form-item>
<img id="code_image" src="" @click="code_image" alt="點選更換圖片">
<el-form-item>
<el-button type="primary" @click="onSubmit">驗證</el-button>
</el-form-item>
</el-form>
</div>
<script>
new Vue({
el: "#app",
data: {
formInline: {
code: '',
key_name: ""
}
},
methods: {
onSubmit() {
if(this.formInline.code!=""){
axios.get("/code?code="+this.formInline.code+"&key_name="+this.formInline.key_name).then(data=>{
if(data.data){
this.$message({
message: '恭喜,驗證成功!',
type: 'success'
});
}else{
this.$message.error('抱歉,驗證錯誤!');
}
});
}else{
this.$message.error('請輸驗證碼!');
}
},
code_image(){
this.formInline.key_name = Math.random();
document.getElementById("code_image").src="/code?key_name="+this.formInline.key_name;
}
},
created(){
this.code_image();
}
})
</script>
</body>
</html>