驗證碼的案例程式碼
阿新 • • 發佈:2018-11-16
//建立一張圖片
//單位:畫素
BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
//透明的玻璃
//向畫板上畫內容之前必須先設定畫筆.
Graphics2D gra = image.createGraphics();
gra.setColor(Color.WHITE);
//從哪個座標開始填充, 後兩個引數,矩形區域
gra.fillRect(0, 0, 200, 100);
List <Integer> randList = new ArrayList<Integer>();
Random random =new Random();
for (int i = 0 ;i<4;i++) {
randList.add(random.nextInt(10));
}
//設定字型
gra.setFont(new Font("宋體",Font.ITALIC|Font.BOLD,40));
Color[] colors = new Color[]{Color.RED,Color.YELLOW,Color.BLUE,Color.GREEN,Color.PINK,Color.GRAY};
for (int i = 0; i < randList.size(); i++) {
gra.setColor(colors[random.nextInt(colors.length)]);
gra.drawString(randList.get(i)+"", i*40, 70+(random.nextInt(21)-10));
}
for (int i = 0; i < 2; i++) {
gra.setColor(colors[random.nextInt(colors.length)]);
//畫橫線
gra.drawLine(0, random.nextInt(101), 200, random.nextInt(101));
}
ServletOutputStream outputStream = resp.getOutputStream();
//工具類
ImageIO.write(image, "jpg", outputStream);
//把驗證碼放入到session中
HttpSession session = req.getSession();
session.setAttribute("code", ""+randList.get(0)+randList.get(1)+randList.get(2)+randList.get(3));