package com.lk.test;
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 RequestServlet extends HttpServlet{
/**
* 定义序列版本号
*/
private static final long serialVersionUID = 1L;
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(){
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < 6; i++) {
stringBuffer.append(chars[random.nextInt(chars.length)]);
}
return stringBuffer.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(random.nextInt(255-c.getRed()),random.nextInt(255-c.getGreen()),random.nextInt(255-c.getBlue()));
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置输出类型
resp.setContentType("image/jpeg");
//获取随机字符串
String randomString = getRandomString();
//随机字符串放入session中
req.getSession(true).setAttribute("randomString", randomString);
//图片宽度
int width=100;
//图片高度
int height=30;
//随机颜色用于字体颜色
Color color = getRandomColor();
//反色用于背景颜色
Color reverseColor = getReverseColor(color);
//创建一个彩色图片
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//获取绘图对象
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(reverseColor);
//绘制随机字符
g.drawString(randomString, 18, 20);
//画最多100个噪音点
for (int i = 0; i < random.nextInt(100); i++) {
//随机噪音点
g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
}
//输出流
ServletOutputStream out = resp.getOutputStream();
//编码器对象 把流转化成JPEG格式
JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(out);
//对图片进行编码
encode.encode(bi);
out.flush();
out.close();
}
}
前台代码:
<script type="text/javascript">
function reloadImage(){
document.getElementById("btn").disabled=true;
document.getElementById("identity").src="RequestServlet?ts="+new Date().getTime();
}
</script>
<img src="RequestServlet" id="identity" οnlοad="btn.disabled=false;">
<input type="button" value="换个图片" id="btn" οnclick="reloadImage()"/>
"RequestServlet“为映射路径