package gssw.oa.util.ww.action;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import gssw.oa.comm.wqg.action.BaseAction;
import gssw.oa.util.ww.MyUtils;
public class UtilAction extends BaseAction {
/**
*
*/
private static final long serialVersionUID = 6509394132825567797L;
private ByteArrayInputStream inputStream;
public String validCodeImage() throws Exception {
// 验证码图片的宽度和高度
int width=150;
int height=50;
BufferedImage buffImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D g=buffImg.createGraphics();
Random random=new Random();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
Font font=new Font("Arial",Font.PLAIN,45);
g.setFont(font);
//画边框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);
//随机长生160条干扰线,防止被其他程序探测到
g.setColor(Color.GRAY);
for(int i=0;i<160;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
int x1=random.nextInt(12);
int y1=random.nextInt(12);
g.drawLine(x, y, x+x1, y+y1);
}
StringBuffer randomCode=new StringBuffer();
int red=0,green=0,blue=0;
String strRand="";
//随机产生4位验证码
for (int i = 0; i < 4; i++) {
red=random.nextInt(255);
green=random.nextInt(255);
blue=random.nextInt(255);
g.setColor(new Color(red,green,blue));
strRand=MyUtils.getRandString();
g.drawString(strRand, 30*i+16, 40);
randomCode.append(strRand);
}
//将4位数字的验证码保存到Session中
getSession().put("randomCode", randomCode.toString());
g.dispose();
ByteOutputStream output=new ByteOutputStream();
ImageOutputStream imageOut=ImageIO.createImageOutputStream(output);
ImageIO.write(buffImg, "JPEG", imageOut);
imageOut.close();
ByteArrayInputStream input=new ByteArrayInputStream(output.getBytes());
setInputStream(input);
//将验证码写入到Cookie中,已便于客户端进行比较
HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();
Cookie[] cookies=request.getCookies();
Cookie cookie=null;
if(null!=cookies){
for (Cookie c : cookies) {
if("loginValidCode".equals(c.getName())){
cookie=c;
break;
}
}
}
if(null==cookie) cookie=new Cookie("loginValidCode","");
cookie.setValue(randomCode.toString());
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
return "validcode";
}
public ByteArrayInputStream getInputStream() {
return inputStream;
}
public void setInputStream(ByteArrayInputStream inputStream) {
this.inputStream = inputStream;
}
}