java 驗證碼

String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; //隨機 Random random = new Random(); //驗證碼,圖片 int fontCount = 4; //生成一張圖片 int width = 60; int height = 30; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //須要得到畫板 Graphics g = bi.getGraphics(); //畫筆的顏色 g.setColor(Color.black); g.fillRect(0, 0, width, height); //畫一張白圖 g.setColor(Color.white); g.fillRect(1, 1, width-2, height-2); //設置字體大小 g.setFont(new Font("宋體",Font.BOLD,24)); //設置字  for(int i = 0 ; i < fontCount; i ++){ //設置顏色 g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); //得到隨機的字 int index = random.nextInt(52); String str = data.substring(index, index+1); //將隨機字 寫入到畫筆 g.drawString(str, (i+1)*(width / (fontCount + 2)),20); } //干擾線 for(int i = 0 ; i < 10;i++){ g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255))); g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); } //設置頭,告訴瀏覽器是一張圖片 response.setContentType("image/jpeg"); //提示瀏覽器不能緩存 /* * <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0">  */ response.setHeader("pragma", "no-cache"); response.setHeader("cache-control", "no-cache"); response.setHeader("expires", "0"); //將生成的圖片寫入到瀏覽器 image/jpeg ImageIO.write(bi, "jpeg", response.getOutputStream());
相關文章
相關標籤/搜索