老規矩,先上效果圖
這是一款比較簡單的驗證碼的實現,只需弄清其原理即可
實現驗證碼只需分三步走
- 創建字節流驗證碼
//在doPost方法中定義寬高
int width = 200;
int height = 100;
BufferedImage imge = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- 美化驗證碼
//美化分幾步走
//改變背景色
Graphics graphics = imge.getGraphics();
graphics.setColor(Color.PINK);
graphics.fillRect(0, 0, width, height);
``
//邊框
graphics.setColor(Color.BLUE);
graphics.drawRect(0, 0, width - 1, height - 1);`
//寫出驗證碼
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random r = new Random();
for (int j = 1; j <= 4; j++) {
int index = r.nextInt(str.length());
char chars = str.charAt(index);
session_str += chars;
graphics.drawString(chars+"", width/5 * j, height/5 * j);
}
//畫線
graphics.setColor(Color.black);
for (int i = 0; i < 10; i++) {
int x1 = r.nextInt(width);
int x2 = r.nextInt(width);
int y1 = r.nextInt(height);
int y2 = r.nextInt(height);
graphics.drawLine(x1, y1, x2, y2);
}
//使用輸出流,將驗證碼顯示
ImageIO.write(imge, "jpg", response.getOutputStream());
這裏就是最原始的驗證碼實現原理了,希望能給大家帶來幫助