java仿Servlet生成驗(yàn)證碼實(shí)例詳解
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序制作、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了新田免費(fèi)建站歡迎大家使用!
實(shí)現(xiàn)原理:使用BufferedImage對(duì)象的Graphics來進(jìn)行繪制,然后輸出成一張圖片進(jìn)行保存
實(shí)現(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); //繪制隨機(jī)干擾線 int total = 100; drawRandLine(gs,total); //繪制驗(yàn)證碼 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
最終實(shí)現(xiàn)效果圖
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!