**先寫個小demo **
知識點
告訴瀏覽器 不要緩存圖片 不然點擊回車的時候 走緩存
response.setHeader("Expires", "-1");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
/**
* 簡單的實現(xiàn)
* @param response
* @throws IOException
*/
private void showDemo1(HttpServletResponse response) throws IOException {
//向瀏覽器打個圖片
//設(shè)置能讓瀏覽器打開 識別圖片
response.setHeader("content-type", "image/jpeg");
// 1、在內(nèi)存中創(chuàng)建一副圖片
BufferedImage bufferedImage=new BufferedImage(100, 20, BufferedImage.TYPE_INT_RGB);
//2拌阴、得到圖片 (畫筆)
java.awt.Graphics graphics= bufferedImage.getGraphics();
// 3上煤、向圖片上寫數(shù)據(jù)
graphics.setColor(Color.RED);//設(shè)置 畫筆的顏色是紅色
//設(shè)置 畫筆的字體 new Font(null, Font.BOLD, 20) 字體雄人、粗細(xì)砂沛、高度
graphics.setFont(new Font(null, Font.BOLD, 20));
graphics.drawString(random(), 0, 20);
//4谴餐、將圖片寫給瀏覽器
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
/**
* 產(chǎn)成一個隨機數(shù) 7位
* @return
*/
private String random() {
Random random=new Random();
String num=random.nextInt(9999999)+"";//產(chǎn)生一個 0~9999999之間的隨機數(shù)
StringBuffer stringBuffer=new StringBuffer();
for (int i = 0; i <7-num.length(); i++) {
stringBuffer.append("0");
}
num=stringBuffer.toString()+num ;
return num;
}
要是修改背景圖片要用到 Graphics2D 次類
Graphics2D graphics=(Graphics2D) bufferedImage.getGraphics();
graphics.setColor(Color.green);//設(shè)置背景 一定要寫在前面
graphics.fillRect (0, 0, 100, 20);// 設(shè)置背景大小累舷。
......
graphics.setColor(Color.RED);//設(shè)置 畫筆的顏色是紅色 字體的顏色
//設(shè)置 畫筆的字體 new Font(null, Font.BOLD, 20) 字體蝇摸、粗細(xì)、高度
graphics.setFont(new Font(null, Font.BOLD, 20));
graphics.drawString(random(), 0, 20);
最后寫個簡單的htmL 來調(diào)用這個 圖片驗證
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="">
用戶名:<input type="text" name="username"><br/>
密碼:<input type="password" name="password"><br>
驗證碼:<input type="text" name="checkcode">![](/Day052/ServletRandomPicture)
<input type="button" value="注冊">
</form>
</body>
</html>
public static void main(String[] args) {
char a='\u597E';
// char a='\u80BB';
System.out.println(a);
}