日期:2014-05-17 浏览次数:20732 次
package com.iCloud.action;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class WaiguaAction extends ActionSupport implements SessionAware{
/**
*
*/
private static final long serialVersionUID = 1L;
private Map<String,Object> session;
private HttpServletResponse response;
private HttpServletRequest request;
private int width = 75;
private int height = 20;
public WaiguaAction(int width, int height) {
// TODO Auto-generated constructor stub
this.width = width;
this.height = height;
}
public String writeImg(OutputStream out) {
/** 应用绘图对象 **/
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D gd = (Graphics2D) bi.getGraphics();
/** 绘制背景 **/
// gd.setColor(getRandColor(100,200));
// gd.fillRect(0, 0, width, height);
// gd.setColor(java.awt.Color.WHITE);
// gd.fillRect(0,0,120,70);
// 红:204 绿:232 蓝:207
gd.setBackground(new Color(204, 232, 207));
// gd.setBackground(new Color(rnd(),rnd(),rnd()));
gd.clearRect(0, 0, width, height);
/** 设置字体 **/
Font font = new Font(getRndFontNames(), Font.PLAIN, 24);
gd.setFont(font);
/** 随机字串 **/
StringBuffer sb = new StringBuffer();
int i;
for (i = 0; i < 4; i++) {
sb.append(filter(rnd()));
}
/** 设置颜色并输出 **/
/**
* 1 所有验证码颜色一致 gd.setColor(new Color(rnd(),rnd(),rnd()));
* gd.drawString(sb.toString(), 0, 16); //这是普通方式,我想让所有字母颜色都不同
**/
/** 2 用随机颜色生成每个验证符 **/
String st = sb.toString();
System.out.println(st); //页面点击刷新验证码,控制台已经可以得到生成了值
// session.put("st", st); //这样保存会报空值异常
// HttpSession session = request.getSession(); //这样保存会报空值异常
// session.setAttribute("rand", st.toString()); //这样保存会报空值异常
while (i > 0) {
/** 随机颜色,并进行色彩限定 **/
gd.setColor(new Color(rnd(), rnd(), rnd()));
gd.drawString(st.substring(i - 1, i), (i - 1) * 16 + 5, 16);
i--;
}
/** 清理现场 **/
gd.dispose();
bi.flush();