你的分享就是我们的动力 ---﹥

用Java生成简单的验证码实例

时间:2013-05-16 16:46来源:www.chengxuyuans.com 点击:

代码简介

用Java生成简单的验证码实例,所上传文件是一个Servlet,自行配置web.xml。部署之后即可使用。

代码片段

package utils;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

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 com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class CheckCode extends HttpServlet {

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("image/jpeg");
		// 图片的内存映像
		BufferedImage image = new BufferedImage(60, 20,
				BufferedImage.TYPE_INT_BGR);
		// 获取画笔对象
		Graphics g = image.getGraphics();

		Random r = new Random();
		g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
		g.fillRect(0, 0, 60, 20);
		g.setColor(new Color(0,0,0));
		String number = String.valueOf(r.nextInt(99999));
		HttpSession session = request.getSession();
		session.setAttribute("number", number);
		g.drawString(number, 5, 15);
		g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
		//压缩jpeg格式
		OutputStream os = response.getOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
		//把BUfferedImage对象中的图像信息编码后
		//向创建对象时指定的输出流输出
		encoder.encode(image);
	}

}

转载注明地址http://www.chengxuyuans.com/code/java/60562.html