controller:
1 2 /** 3 * 獲取登錄的驗證碼 4 * @param request 5 * @param response 6 */ 7 public void getLoginCode(HttpSession session,HttpServletRequest request, 8 HttpServletResponse response) throws Exception{ 9 // 獲取驗證碼以及圖片 10 Map<String,Object> map = CodeUtil.generateCodeAndPic(); 11 // 將驗證碼存入Session 12 session.setAttribute("imageCode",map.get("code")); 13 // 獲取圖片 14 BufferedImage image = (BufferedImage) map.get("codePic"); 15 // 轉成base64 16 BASE64Encoder encoder = new BASE64Encoder(); 17 ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流 18 ImageIO.write(image, "png", baos);//寫入流中 19 byte[] bytes = baos.toByteArray();//轉換成字節 20 String png_base64 = encoder.encodeBuffer(bytes).trim();//轉換成base64串 21 //刪除 \r\n 22 png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", ""); 23 Map<String,String> maps = new HashMap<>(); 24 maps.put("code","" + map.get("code")); 25 maps.put("address",png_base64); 26 JSONObject jsonObject = JSONObject.fromObject(maps); 27 PrintWriter writer = response.getWriter(); 28 writer.print(jsonObject); 29 writer.flush(); 30 writer.close(); 31 }
private static int width = 180; private static int height = 40; private static int codeCount = 4; private static int xx = 30; private static int fontHeight = 36; private static int codeY = 32; private static char[] codeSequence = { '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; /** * 生成驗證碼圖片 * @return */ public static Map<String,Object> generateCodeAndPic(){ //定義圖像buffer BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics graphics = bufferedImage.getGraphics(); //創建一個隨機數類 Random random = new Random(); // 將圖像填充為白色 graphics.setColor(Color.WHITE); // 填充圖像 graphics.fillRect(0,0,width,height); // 創建字體,字體的大小應該根據圖片的高度來定 Font font = new Font("Fixedsys", Font.BOLD, fontHeight); // 設置字體 graphics.setFont(font); // 畫邊框 graphics.setColor(Color.black); graphics.drawRect(0,0,width-1,height-1); // 隨機產生30條干擾線,讓圖形碼不便於被其他程序檢測到 graphics.setColor(Color.black); for (int i=0;i<30;i++){ int x = random.nextInt(width); int y = random.nextInt(height); int x1 = random.nextInt(12); int y1 = random.nextInt(12); graphics.drawLine(x,y,x + x1,y + y1); } // randomCode用於保存隨機生成的二維碼,便於用戶登錄時驗證 StringBuffer randomCode = new StringBuffer(); int red = 0, green=0,blue = 0; // 隨機產生codeCount數字的驗證碼 for (int i =0;i<codeCount;i++){ // 得到隨機的驗證碼數字 String code = String.valueOf(codeSequence[random.nextInt(36)]); // 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色都不一樣 red = random.nextInt(255); blue = random.nextInt(255); green = random.nextInt(255); // 用隨機產生的顏色將驗證碼放到圖像中 graphics.setColor(new Color(red,green,blue)); graphics.drawString(code,(i + 1) * xx,codeY); // 將產生的四個隨機數組合在一起 randomCode.append(code); } Map<String,Object> map = new HashMap<>(); // 存放驗證碼 map.put("code",randomCode); // 存放生成的驗證碼BufferedImage對象 map.put("codePic",bufferedImage); return map; }