登入頁面生成彩色驗證碼圖片,使用者需輸入帳號、密碼、驗證碼三重驗證。
package pic;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class makeCertPic {
private char[] mapTable = {
'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'
};
public String getCertPic(int width, int height, OutputStream os) {
if (width <= 0) width = 60;
if (height <= 0) height = 20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 背景
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
// 邊框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);
// 隨機 4 位驗證碼
StringBuilder strEnsure = new StringBuilder();
for (int i = 0; i < 4; i++) {
strEnsure.append(mapTable[(int)(mapTable.length * Math.random())]);
}
// 繪製字符 (錯位增加識別難度)
g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18));
g.setColor(Color.BLACK);
String code = strEnsure.toString();
g.drawString(code.substring(0,1), 8, 17);
g.drawString(code.substring(1,2), 20, 15);
g.drawString(code.substring(2,3), 35, 18);
g.drawString(code.substring(3,4), 45, 15);
// 干擾點
Random rand = new Random();
for (int i = 0; i < 10; i++) {
g.drawOval(rand.nextInt(width), rand.nextInt(height), 1, 1);
}
g.dispose();
try {
ImageIO.write(image, "JPEG", os);
} catch (IOException e) {
return "";
}
return code;
}
}
BufferedImage 離屏渲染,無需臨時檔案。mapTable 排除易混淆字元 (如 o/0, l/1)。ImageIO.write(image, "JPEG", os) 直接輸響應流,適合 Servlet/JSP 輸出 image/jpeg。