1. 程式人生 > >Java使用imageio、awt生成圖片驗證碼

Java使用imageio、awt生成圖片驗證碼

static rem auto put 驗證碼 encode width nal cond

1、生成驗證碼工具類

public class CheckCodeTool {
    private Integer width = 80;
    private Integer height = 38;
    
      public String getCheckCode(BaseForm baseForm) {
            /*
             * 繪圖
             */
            // step1,創建一個內存映像對象(畫板)
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            
// step2,獲得畫筆 Graphics g = image.getGraphics(); // step3,給筆上色 //Random r = new Random(); SecureRandom r = new SecureRandom(); // g.setColor(new Color(r.nextInt(255), r.nextInt(255),r.nextInt(255))); // step4,給畫板設置背景顏色 g.fillRect(0, 0, width, height);
// step5,繪制一個隨機的字符串 String number = getNumber(); g.setColor(new Color(0, 0, 0)); //存儲到redis(用於登錄校驗) if (baseForm != null && StringUtils.isNotEmpty(baseForm.getSessionId())) { String redisCheckCodeId = "CheckCodeId"; try
{ if (RedisUtil.getInstance().isExists(redisCheckCodeId)) { RedisUtil.getInstance().remove(redisCheckCodeId); } RedisUtil.getInstance().setStringWithSeconds(redisCheckCodeId,number,60);//1分鐘時效 } catch (Exception e) { System.out.println("getCheckCode:error:" + e.toString()); } } // new Font(字體,風格,大小) g.setFont(new Font(null, Font.ITALIC, 20)); g.drawString(number, 5, 25); // step6,加一些幹擾線 for (int i = 0; i < 8; i++) { g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255))); g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height)); } /* * 壓縮圖片並輸出到客戶端(瀏覽器) */ ByteArrayOutputStream out = new ByteArrayOutputStream(); String base64String = ""; try { ImageIO.write(image, "jpeg", out); base64String = Base64Utils.encode(out.toByteArray()); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } return base64String; } // 生成隨機數作為驗證碼 private String getNumber() { String number = ""; String pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; SecureRandom r = new SecureRandom(); for (int i = 0; i < 4; i++) { number += pool.charAt(r.nextInt(pool.length())); } return number; } }

2、測試驗證類

public class CheckCodeTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CheckCodeTool checkCodeTool = new CheckCodeTool();
        String checkCode = checkCodeTool.getCheckCode(new BaseForm());
        System.out.println(checkCode);
    }

}

輸出:

/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGB ......

將base64String字符串傳遞給前端,即可顯示圖片驗證碼。

Java使用imageio、awt生成圖片驗證碼