@RequestMapping("/imagecode")
public void image(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException, ServletException {
//告訴客戶端不使用緩存
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setIntHeader("expires", 0);
//生成驗證碼圖片
BufferedImage img = drawValidateCode(request);
//將圖片對象以流的方式輸出的客戶端
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(img, "jpg", response.getOutputStream());
response.getOutputStream().close();
//return "redirect:hello";
}
private BufferedImage drawValidateCode(HttpServletRequest request){
int width = 110;
int height = 25;
//在內存中創建一個圖片對象
BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//創建一個畫筆
Graphics g = img.getGraphics();
//給圖片添加顏色
g.setColor(Color.PINK); //設置一個顏色
g.fillRect(1,1,width-2,height-2); //填充顏色
//給邊框一個色
g.setColor(Color.RED);
g.drawRect(0, 0, width - 1, height - 1);//設置邊框的顯示座標
//設置文本樣式l
g.setColor(Color.BLUE);
g.setFont(new Font("宋體", Font.BOLD | Font.ITALIC, 15));
//給圖片添加文本
Random rand = new Random();
String str = "";
int position = 20;
for (int i = 0; i < 4; i++) {
int rd = rand.nextInt(10);
str += rd;
g.drawString(rd + "", position, 20); //給圖片填充文本
position += 20;
}
//Session 中
request.getSession().setAttribute("SESSION_IMAGE", str);
//添加9條幹擾線
for (int i = 0; i < 9; i++) {
g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
}
return img;
}
使用BufferedImage生成驗證碼(方法)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.