Java web實現(xiàn)動態(tài)圖片驗證碼的示例代碼
驗證碼
防止惡意表單注冊
生成驗證碼圖片
定義寬高
int width = 100; int height = 50;
使用BufferedImage再內(nèi)存中生成圖片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
繪制背景和邊框
Graphics g = image.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); g.setColor(Color.BLACK); g.drawRect(0, 0, width - 1, height - 1);
創(chuàng)建隨機字符集和隨機數(shù)對象
//字符集 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgjijklmnopqrstuvwxyz"; //隨機數(shù) Random ran = new Random();
創(chuàng)建隨機顏色生成方法
private Color getRandomColor(Random random) { //獲取隨機顏色 int colorIndex = random.nextInt(3); switch (colorIndex) { case 0: return Color.BLUE; case 1: return Color.GREEN; case 2: return Color.RED; case 3: return Color.YELLOW; default: return Color.MAGENTA; } }
繪制驗證碼字符
//繪制驗證碼 for (int i = 0; i < 4; i++) { //獲取隨機字符 int index = ran.nextInt(str.length()); char ch = str.charAt(index); //獲取隨機色 Color randomColor = getRandomColor(ran); g.setColor(randomColor); //設(shè)置字體 Font font = new Font("宋體", Font.BOLD, height / 2); g.setFont(font); //寫入驗證碼 g.drawString(ch + "", (i == 0) ? width / 4 * i + 2 : width / 4 * i, height - height / 4); }
繪制干擾線
//干擾線 for (int i = 0; i < 10; i++) { int x1 = ran.nextInt(width); int x2 = ran.nextInt(width); int y1 = ran.nextInt(height); int y2 = ran.nextInt(height); Color randomColor = getRandomColor(ran); g.setColor(randomColor); g.drawLine(x1, x2, y1, y2); }
使用ImageIO輸出圖片
ImageIO.write(image, "jpg", resp.getOutputStream());
成果圖
實現(xiàn)刷新效果
新建html頁面
使用img標簽實現(xiàn)圖片展示
<img id="identcode" src="identcode"> <a id="refesh" href="">看不清,換一張</a>
使用js實現(xiàn)刷新效果
//點擊圖片時 var img = document.getElementById("identcode"); img.onclick = function (){ refesh(); } //點擊連接時 var a = document.getElementById("refesh"); a.onclick = function (){ refesh(); //返回false防止a標簽?zāi)Jhref行為 return false; } function refesh() { /** * 由于路徑相同時瀏覽器會自動調(diào)用緩存中的圖片 * 所以在連接后加時間戳解決此問題 */ var date = new Date().getTime(); img.src = "identcode?" + date; }
效果
項目源碼
https://github.com/xiaochen0517/StudySpace/tree/master/idea/TestDemo3
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合Ip2region獲取IP地址和定位的詳細過程
ip2region v2.0 - 是一個離線IP地址定位庫和IP定位數(shù)據(jù)管理框架,10微秒級別的查詢效率,提供了眾多主流編程語言的 xdb 數(shù)據(jù)生成和查詢客戶端實現(xiàn) ,這篇文章主要介紹了SpringBoot整合Ip2region獲取IP地址和定位,需要的朋友可以參考下2023-06-06線程池滿Thread?pool?exhausted排查和解決方案
這篇文章主要介紹了線程池滿Thread?pool?exhausted排查和解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11SpringBoot?如何使用sharding?jdbc進行分庫分表
這篇文章主要介紹了SpringBoot?如何使用sharding?jdbc進行分庫分表,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02