傳統字母數字驗證碼字符集小易被識別,本文實現基於中文常用字的彩色驗證碼,生成 6 個隨機漢字,配合干擾線、隨機字體/顏色/位置,顯著提高識別難度。
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
Color getRandColor(Random r, int fc, int bc) {
if(fc>255) fc=255; if(bc>255) bc=255;
return new Color(fc+r.nextInt(bc-fc), fc+r.nextInt(bc-fc), fc+r.nextInt(bc-fc));
}
%>
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
int width=176, height=30;
String base = "的一是我不在人..."; // 3000+ 常用漢字 Unicode 轉義
int len = base.length();
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
Random random = new Random();
g.setColor(getRandColor(random,200,250)); g.fillRect(0,0,width,height); // 背景
String[] fonts = {"宋體","新宋體","黑體","楷體","隸書"};
// 干擾線
g.setColor(getRandColor(random,160,200));
g.setFont(new Font("Times New Roman",Font.PLAIN,14));
for(int i=0;i<6;i++) g.drawString("*********************************************",0,5*(i+2));
StringBuilder sRand = new StringBuilder();
for(int i=0;i<6;i++) {
String ch = base.substring(random.nextInt(len), random.nextInt(len)+1);
sRand.append(ch);
g.setColor(getRandColor(random,10,150));
g.setFont(new Font(fonts[random.nextInt(fonts.length)], Font.BOLD, 18+random.nextInt(6)));
g.drawString(ch, 24*i+10+random.nextInt(8), 24);
}
session.setAttribute("rand", sRand.toString()); // 存入 Session 驗證
g.dispose();
ImageIO.write(img, "JPEG", response.getOutputStream());
%>