一个产生随机图片验证码的示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wyf.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class PrintServlet extends HttpServlet {
// 设置要随机生成的数
public static final char[] chars = { '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
public static Random random = new Random(); // 随机生成数
public static String getRandomString(){ // 随机获取6位数
StringBuffer buffer = new StringBuffer(); // 字符串缓存
boolean[] result = new boolean[chars.length];
int i = 0;
while(i<6){ // 总共产生6个不同的随机数
int index = random.nextInt(chars.length);
if(result[index]){ //表示该随机数已经产生了
continue;
}
result[index]= true;
buffer.append(chars[index]); // 每次获得一个随机产生的字符
i++;
}
return buffer.toString();
}
public static Color getRandomColor(){ //获取随机产生的颜色
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
public static Color getRandomColor(Color c){ // 返回颜色的反色
return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("image/jpeg"); // 设置输出类型
String randomString = getRandomString(); // 随机字符串
req.getSession(true).setAttribute("randomString", randomString); // 放到sessio中
int width = 200; // 设置图片宽度
int height = 50; // 设置图片的高度
Color color = getRandomColor();// 设定随机产生颜色, 用于设定背景颜色
Color reverse = getRandomColor(); // 反色, 用于设定前景色
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 创建一个彩色图片
Graphics2D g = bi.createGraphics(); // 获取绘图对象
g.setFont(new Font("宋体", Font.BOLD, 16)); // 设置随机数的字体
g.setColor(color); // 设置随机数的颜色
g.fillRect(0, 0, width, height);// 绘制随机数的背景
g.setColor(reverse); //设置随机数的颜色
g.drawString(randomString, 18, 20); // 绘制随机字符
for(int i = 0,n = random.nextInt();i < n; i++){ // 设置随机数中最多有100个噪点
g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1); // 随机噪音点
}
ServletOutputStream out = resp.getOutputStream(); // 将随机数转换为JPEG图片格式
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // 设置编码器
encoder.encode(bi); // 对图片进行编码
out.flush(); // 输出到客户端
}
}
附上html:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Identity.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<script type="text/javascript">
function reloadImage(){
document.getElementById('btn').disabled = true;
document.getElementById('identity').src ='servlet/IdentityServlet?ts='+new Date().getTime();
}
</script>
<img src="PrintServlet" id="PrintServlet" onload="btn.disabled = false;"/>
<input type=button value="换个图片" onclick="reloadImage()" id="btn">
</body>
</html>
web.xml配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<servlet>
<description>
</description>
<display-name>PrintServlet</display-name>
<servlet-name>PrintServlet</servlet-name>
<servlet-class>com.wyf.servlet.PrintServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PrintServlet</servlet-name>
<url-pattern>/PrintServlet</url-pattern>
</servlet-mapping>