Java验证码实现

package com.crow.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ImageCodeController {

	/**
	 * 图片验证码
	 * 
	 * @param response HttpServletResponse
	 * @param time     随机时间
	 * @throws Exception 图片异常
	 */
	@RequestMapping("/code.action")
	public void imageCode(HttpServletRequest request, HttpServletResponse response, String time) throws Exception {
		// 验证码的规范:一般我们验证码不需要0和o,iL和1,2和z不需要
		String[] code = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C","D","E","F","G","H","J","M","N","P","Q","R","S","T","U"
				,"V","W","X","Y"};
		// 这三个参数分别代表图片的宽高以及图片的色调类型
		BufferedImage bi = new BufferedImage(270, 45, BufferedImage.TYPE_INT_RGB);
		// 获取画笔
		Graphics g = bi.getGraphics();
		// 绘制背景
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 270, 45);

		// 绘制验证码
		// 获取验证码
		String valiCode = "";
		for (int i = 0; i < 4; i++) {
			Random r = new Random();
			int index = r.nextInt(code.length);
			valiCode += code[index];
		}
		HttpSession hs = request.getSession();
		hs.setAttribute("valiCode", valiCode);

		BufferedImage newImgCode = newImgCode(120, 40, valiCode);
		ImageIO.write(newImgCode, "jpg", response.getOutputStream()); // 将图片验证码输出
	}

	/**
	 * 获取图片验证码
	 * 
	 * @param width  宽
	 * @param height 高
	 * @param code   验证码
	 * @return 图片验证码
	 */
	public static BufferedImage newImgCode(int width, int height, String code) {
		int size = code.length();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics g = image.getGraphics(); // 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
		g.fillRect(0, 0, width, height);
		g.setColor(new Color(245, 244, 208)); // 默认文字颜色
		g.setFont(new Font("Arial", Font.CENTER_BASELINE, 24)); // 设置默认文字大小
		// 画干拢线
		Random random = new Random();
		for (int i = 0; i <= size * 4; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(13);
			int yl = random.nextInt(15);
			g.drawLine(x, y, x + xl, y + yl);
		}
		// 将文字写入图片
		String randomString = code;
		for (int i = 1; i <= size; i++) {
			g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121))); // 设置颜色区间变化
			g.drawString(randomString.charAt(i - 1) + "", 18 * i, 26);
		}
		return image;
	}
}

猜你喜欢

转载自blog.csdn.net/IT_Java_Roy/article/details/88610644
今日推荐