`

生成随机验证码的方式

 
阅读更多
package cn.identity;

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;

/**
 * Servlet implementation class IdentityServlet
 */
public class IdentityServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/*不包含0,O,I,1,这几个难区分*/
	public static final char[] CHARS={'1','2','3','4','5','6','7','8','9','A','B','C','D',
		'E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X'};
	/*构建一个随机数*/
	public static Random random=new Random();
	
	/**
	 * 获取4位随机数
	 * @return
	 */
	public static String getRandomString(){
		StringBuffer buffer=new StringBuffer();//字符串缓存
		for(int i = 0 ;i < 4 ;i++){
			buffer.append(CHARS[random.nextInt(CHARS.length)]);//随机去四个,然后追加在每个的后面
		}
		return buffer.toString();//返回这四个随机值,组合成一个字符串
	}
	
	/**
	 * 获取随机颜色
	 * @return
	 */
	public static Color getRandomColor(){
		return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
	}
	
	/**
	 * 回去随机颜色的相反颜色
	 * @param c
	 * @return
	 */
	public static Color getReverseColor(Color c){
		return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 response.setContentType("image/jpeg");//设置输出类型
		String randomString= getRandomString();//
		request.getSession(true).setAttribute("randomString", randomString);
		int width=80;
		int height=20;
		Color color=getRandomColor();
		
		Color reverse=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(reverse);
		g.drawString(randomString, 18, 15);//获取session中的字符串,放在图片上
		
		//绘制干扰点
		for(int i=0 ,n=random.nextInt(20);i<n;i++){
			g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
		}
		ServletOutputStream out=response.getOutputStream();
		//转化成jpeg格式
		JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
		//编码器
		encoder.encode(bi);
		//输出到客户端
		out.flush();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics