分类:
2008-10-16 18:23:24
package com.work.core.image;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author wangmj
* 生成随机的验证码!防止暴利破解。
*/
public class AuthImage extends HttpServlet {
private static Log log = LogFactory.getLog(AuthImage.class);
/**
*
*/
private static final long serialVersionUID = 8165458985542870320L;
//设置图形验证码中的字符串的字体的大小
private Font mFont = new Font("Arial Black", Font.PLAIN, 16);
public void init() throws ServletException {
super.init();
}
/**
* 生成随机颜色
* @param fc
* @param bc
* @return
*/
Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
/* (non-doc)
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//生成相应的service方法
//阻止生成的页面内容被缓存,保证每次重新生成随机验证码
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
//指定图形验证码图片的大小;
int width = 80;//宽度
int height = 20;//高度
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 准备在图片中绘制内容
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(1, 1, width - 1, height - 1);
g.setColor(new Color(102, 102, 102));
g.drawRect(0, 0, width - 1, height - 1);
g.setFont(mFont);
[1]