2017年9月 的存档
20179 月15

使用Java API绘制验证码图片

import java.awt.Color;
import java.awt.Font;
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;

/**
 * 生成验证码,将验证码绘制成一张图片返回浏览器
 * 
 * @author FreeDroid
 *
 */
public class CheckcodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest request, 
              HttpServletResponse response) throws 
                     ServletException, IOException {
		/*
		 * step1.绘图
		 */
		Random r = new Random();
		//从getString()方法取出A-Z,0-9的指定长度随机字符串
		String number = getString(5);
		//先创建一个画布(内存映像对象)
		BufferedImage image = new BufferedImage(80, 30, BufferedImage.TYPE_INT_BGR);
		//获得画笔
		Graphics g = image.getGraphics();
		//给画笔设置颜色
		g.setColor(new Color(255, 255, 255));
		//给画布设置背景颜色
		g.fillRect(0, 0, 80, 30);
		//设置字体
		g.setFont(new Font(null, Font.BOLD|Font.ITALIC, 20));
		//给每个字符设置随机颜色,并画到画布上
		for (int i = 0; i < number.length(); i++) {
			//给画笔设置颜色
			g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
			//在画布上画字符
			g.drawString(String.valueOf(number.charAt(i)), i*15, 25);
		}
		//加一些干扰线
		for (int i = 0; i < 8; i++) {
			//给画笔设置颜色
			g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
			//在画布范围内画线
			g.drawLine(r.nextInt(80), r.nextInt(30), r.nextInt(80), r.nextInt(30));
		}
		
		/*
		 * step2.将图片压缩,然后输出
		 */
		//设置响应内容类型为JPEG格式的图片
		response.setContentType("image/jpeg");
		//获得字节输出流(图片是二进制数据)
		OutputStream os = response.getOutputStream();
		//将原始图片(image)按照指定的算法压缩(jpeg)
                //然后将压缩之后得到的字节写入response对象。
		javax.imageio.ImageIO.write(image, "jpeg", os);
		os.close();		
	}

	/**
	 * 随机生成指定长度的大写字母和数字组合
	 * @param length
	 * @return
	 */
	private String getString(int length) {
		StringBuilder str = new StringBuilder();
		Random r = new Random();
		//取出大写字母
		for (int i = 0; i < 26; i++) {
			str.append((char) ('A' + i));
		}
		//取出数字
		for (int i = 0; i < 10; i++) {
			str.append((char) ('0' + i));
		}
		//从字符串str随机取length个字符放进str2组成新的字符串
		StringBuilder str2 = new StringBuilder();
		for (int i = 0; i < length; i++) {
			str2.append(str.charAt(r.nextInt(str.length())));
		}
		return str2.toString();
	}
	
}