java仿Servlet生成驗證碼實例詳解
網(wǎng)站建設哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、小程序制作、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了新田免費建站歡迎大家使用!
實現(xiàn)原理:使用BufferedImage對象的Graphics來進行繪制,然后輸出成一張圖片進行保存
實現(xiàn)代碼及詳解:
public class validateCode{ private static Random rand = new Random(); public static void main(String[] args){ int val1 = rand.nextInt(9); int val2 = rand.nextInt(9); int val3 = rand.nextInt(9); int val4 = rand.nextInt(9); String val = val1 + " " + val2 + " " + val3 + " " + val4' BufferedImage buf = drawImage(val); //將最終的圖片保存到D://cheng.png下 ImageIO.write(buf,"png",new File("D://cheng.png"); } public static BufferedImage drawImage(String code){ int height = 30; int width = 60; BufferedImage buf = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics2D gs = buf.createGraphics(); gs.setBackground(Color.black); gs.drawRect(0,0,width,height); //繪制隨機干擾線 int total = 100; drawRandLine(gs,total); //繪制驗證碼 Font font = new Font("行楷",Font.BOLD,20); gs.setFont(font); gs.setColor(getRandColor(155,255)); gs.drawString(code,5,20); return buf; } public static void drawRandLine(Graphics2D gs,int total){ for(int i=0; i<total; i++){ int x1 = rand.nextInt(width); int x2 = rand.nextInt(width); int y1 = rand.nextInt(height); int y2 = rand.nextInt(height); //設置隨機顏色 gs.setColor(getRandColor(0,155)); gs.drawLine(x1,y1,x2,y2); } } public static Color getRandColor(int from,int to){ int r = from + rand.nextInt(to-from); int g = from + rand.nextInt(to-from); int b = from + rand.nextInt(to-from); return new Color(r,g,b); }
最終實現(xiàn)效果圖
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
分享標題:java仿Servlet生成驗證碼實例詳解
網(wǎng)站鏈接:http://jinyejixie.com/article40/jdosho.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設計、網(wǎng)站建設、虛擬主機、網(wǎng)站制作、服務器托管、網(wǎng)站營銷
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)