package my;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.Color;
@SuppressWarnings("serial")
public class GetImageServlet extends HttpServlet {
/**
* 如果提交方式是POST则调用GET方法
*/
public void doPost(HttpServletRequest request,HttpServletResponse
response)
throws ServletException,IOException {
doGet(request,response);
}
/**
* 定义一些全局变量
*/
private static final long serialVersionUID = 1L;
//验证码图片的宽度。
private int width=60;
//验证码图片的高度。
private int height=20;
//验证码字符个数
private int codeCount=4;
private int x=0;
//字体高度
private int fontHeight;
private int codeY;
char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P','Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
/**
* 初始化验证图片属性
*/
public void init() throws ServletException {
//从web.xml中获取初始信息
//宽度
String strWidth=this.getInitParameter("width");
//高度
String strHeight=this.getInitParameter("height");
//字符个数
String strCodeCount=this.getInitParameter("codeCount");
//将配置的信息转换成数值
try
{
if(strWidth!=null && strWidth.length()!=0)
{
width=Integer.parseInt(strWidth);
}
if(strHeight!=null && strHeight.length()!=0)
{
height=Integer.parseInt(strHeight);
}
if(strCodeCount!=null && strCodeCount.length()!=0)
{
codeCount=Integer.parseInt(strCodeCount);
}
}
catch(NumberFormatException e)
{}
x=width/(codeCount+3);
fontHeight=height-4;
codeY=height-5;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
GetImage rc = new GetImage();
try{
rc.getRandcode(request,response);
}catch(Exception e){
System.err.println(e);
}
}
//定义一个内部类
class GetImage
{
/**
* 随机取得一个字体
* @param Random random 随机数
* @return Font 返回一个新字体
*/
private synchronized Font getsFont(Random random){
return new Font("Fixedsys",Font.CENTER_BASELINE,fontHeight);
}
/**
* 返回一个随机颜色
* @param int fc 随机数
* @param int bc 随机数
* @param Random random 随机数
* @return Color 返回一个新颜色
*/
synchronized Color getRandColor(int fc,int bc,Random random){
if(fc>255) fc=255;
if(bc>255) bc=255;
int r=fc+random.nextInt(bc-fc-6);
int g=fc+random.nextInt(bc-fc-4);
int b=fc+random.nextInt(bc-fc-8);
return new Color(r,g,b);
}
/**
* 生成随机数图片
*/
public synchronized void getRandcode(HttpServletRequest
request,HttpServletResponse response)throws Exception{
//定义图像buffer
BufferedImage buffImg = new BufferedImage(
width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
//创建一个随机数生成器类
Random random = new Random();
//设置背景色
g.setColor(getRandColor(123,250,random));
g.fillRect(0, 0, width, height);
//设置字体。
g.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,18));
//产生随机线
g.setColor(getRandColor(111,133,random));
for (int i=0;i<width-98;i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.drawLine(x,y,x+xl,y+yl);
}
//产生随机点
g.setColor(getRandColor(111,255,random));
//画边框。
g.setColor(getRandColor(120,230,random));
g.drawRect(0, 0, width - 1, height - 1);
// randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
StringBuffer randomCode = new StringBuffer();
// 随机产生codeCount数字的验证码。
for (int i = 0; i < codeCount; i++) {
// 得到随机产生的验证码。
String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
g.setFont(getsFont(random));
// 用随机产生的颜色将验证码绘制到图像中。
g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
char[] a={'1','2','3','4'};
String b = String.valueOf(a[random.nextInt(4)]);
g.translate(new Integer(b),new Integer(b)-2);
g.drawString(strRand, (i+1) * x, codeY);
// 将产生的随机数组合在一起。
randomCode.append(strRand);
}
// 将验证码保存到Session中。
HttpSession session = request.getSession();
session.setAttribute("YourValidateCode", randomCode.toString());
// 将图像输出到Servlet输出流中。
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
}
}