新建一个ImageServlet
public class ImageServlet extends HttpServlet {
//不包含0,0,1,i 等等难辨认的字符
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',
'X','Y','Z'};
public static Random random=new Random(); //随机数
//获取6为随即数
public static String getRandomString(){
StringBuffer buffer =new StringBuffer() ; //字符串缓存
for(int i=0;i<6;i++){ //循环6次
//每次取一个随机字符
buffer.append(chars[random.nextInt(chars.length)]);
}
return buffer.toString();
}
//取出随即的颜色
public static Color getRandomColor(){
return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
}
//返回某颜色的反色
public static Color getReverseColor(Color c){
return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
}
/**
* doGet()方法
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg"); //设置输出类型
String randomString=getRandomString();
request.getSession(true).setAttribute("randomString", randomString); //放到session中
int width=100; //图片的宽
int height=30; //图片的高
Color color=getRandomColor(); //随即颜色 用于背景色
Color reverse=getReverseColor(color); //反色,用于前景色
BufferedImage bi =new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D g=bi.createGraphics(); //获取绘图对象
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16)); //设置字体
g.setColor(color); //设置颜色
g.fillRect(0, 0, width, height); //绘制背景
g.setColor(reverse); //设置颜色
g.drawString(randomString, 18, 20); //绘制随机字符
//画最多100个
for(int i=0, n=random.nextInt(100);i<n;i++){
//随即
g.drawRect(random.nextInt(width),random.nextInt(height),1,1);
}
//转成JPEG 格式
ServletOutputStream out=response.getOutputStream();
//编译器
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
//对图片进行编码
encoder.encode(bi);
//输出到客户端
out.flush();
}
/**
* doPost()方法
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
然后在index,jsp页面:
<html>
<script type="text/javascript">
function reloadImage(){
document.getElementById('btn').disabled=true;
document.getElementById("imageid").src='ImageServlet?ts='+new Date().getTime();
}
</script>
<body>
<img src="ImageServlet" id="imageid" οnlοad="btn.disabled=false"/>
<input type=button value="换个图片" οnclick="reloadImage()" id="btn">
</body>
</html>
页面效果: