图形验证码工具类



import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 验证码工具类
 * 
 */
public class CaptchaUtil {
	// 图片的宽度。
	private int width = 160;
	// 图片的高度。
	private int height = 40;
	// 验证码字符个数
	private int codeCount = 4;
	// 验证码干扰线数
	private int lineCount = 20;
	// 验证码
	private String code = null;
	// 验证码图片Buffer
	private BufferedImage buffImg = null;
	Random random = new Random();

	public CaptchaUtil() {
		creatImage();
	}

	public CaptchaUtil(int width, int height) {
		this.width = width;
		this.height = height;
		creatImage();
	}

	public CaptchaUtil(int width, int height, int codeCount) {
		this.width = width;
		this.height = height;
		this.codeCount = codeCount;
		creatImage();
	}

	public CaptchaUtil(int width, int height, int codeCount, int lineCount) {
		this.width = width;
		this.height = height;
		this.codeCount = codeCount;
		this.lineCount = lineCount;
		creatImage();
	}

	// 生成图片
	private void creatImage() {
		// 字体的宽度
		int fontWidth = width / codeCount;
		// 字体的高度
		int fontHeight = height - 5;
		int codeY = height - 8;

		// 图像buffer
		buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = buffImg.getGraphics();
		//Graphics2D g = buffImg.createGraphics();
		// 设置背景色
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);


		// 设置字体
		//Font font1 = getFont(fontHeight);
		Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
		g.setFont(font);

		// 设置干扰线
		for (int i = 0; i < lineCount; i++) {
			int xs = random.nextInt(width);
			int ys = random.nextInt(height);
			int xe = xs + random.nextInt(width);
			int ye = ys + random.nextInt(height);
			g.setColor(getRandColor(1, 255));
			g.drawLine(xs, ys, xe, ye);
		}

		// 添加噪点
		float yawpRate = 0.01f;// 噪声率
		int area = (int) (yawpRate * width * height);
		for (int i = 0; i < area; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);

			buffImg.setRGB(x, y, random.nextInt(255));
		}

		String str1 = randomStr(codeCount);// 得到随机字符
		this.code = str1;
		for (int i = 0; i < codeCount; i++) {
			String strRand = str1.substring(i, i + 1);
			g.setColor(getRandColor(1, 255));
			// g.drawString(a,x,y);
			// a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处

			g.drawString(strRand, i * fontWidth + 3, codeY);
		}
	}

	// 得到随机字符
	private String randomStr(int n) {
		String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
		String str2 = "";
		int len = str1.length() - 1;
		double r;
		for (int i = 0; i < n; i++) {
			r = (Math.random()) * len;
			str2 = str2 + str1.charAt((int) r);
		}
		return str2;
	}

	// 得到随机颜色
	private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	/**
	 * 产生随机字体
	 */
	private Font getFont(int size) {
		Random random = new Random();
		Font[] font = new Font[5];
		font[0] = new Font("Ravie", Font.PLAIN, size);
		font[1] = new Font("Antique Olive Compact", Font.PLAIN, size);
		font[2] = new Font("Fixedsys", Font.PLAIN, size);
		font[3] = new Font("Wide Latin", Font.PLAIN, size);
		font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size);
		return font[random.nextInt(5)];
	}

	// 扭曲方法
	private void shear(Graphics g, int w1, int h1, Color color) {
		shearX(g, w1, h1, color);
		shearY(g, w1, h1, color);
	}

	private void shearX(Graphics g, int w1, int h1, Color color) {

		int period = random.nextInt(2);

		boolean borderGap = true;
		int frames = 1;
		int phase = random.nextInt(2);

		for (int i = 0; i < h1; i++) {
			double d = (double) (period >> 1)
					* Math.sin((double) i / (double) period
					+ (6.2831853071795862D * (double) phase)
					/ (double) frames);
			g.copyArea(0, i, w1, 1, (int) d, 0);
			if (borderGap) {
				g.setColor(color);
				g.drawLine((int) d, i, 0, i);
				g.drawLine((int) d + w1, i, w1, i);
			}
		}
	}

	private void shearY(Graphics g, int w1, int h1, Color color) {

		int period = random.nextInt(40) + 10; // 50;

		boolean borderGap = true;
		int frames = 20;
		int phase = 7;
		for (int i = 0; i < w1; i++) {
			double d = (double) (period >> 1)
					* Math.sin((double) i / (double) period
					+ (6.2831853071795862D * (double) phase)
					/ (double) frames);
			g.copyArea(i, 0, 1, h1, 0, (int) d);
			if (borderGap) {
				g.setColor(color);
				g.drawLine(i, (int) d, i, 0);
				g.drawLine(i, (int) d + h1, i, h1);
			}
		}
	}

	public void write(OutputStream sos) throws IOException {
		ImageIO.write(buffImg, "png", sos);
		sos.close();
	}

	public BufferedImage getBuffImg() {
		return buffImg;
	}

	public String getCode() {
		return code.toLowerCase();
	}



	public static void main(String[] args) {
		CaptchaUtil captchaUtil = new CaptchaUtil(200, 50);
        //测试  将验证码保存到这个文件里
		File file = new File("C:\\Users\\gc\\Desktop\\captchaCode.png");
		try {
			OutputStream fileOutputStream = new FileOutputStream(file);
            //输出方向(输出流)
			captchaUtil.write(fileOutputStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}







}

 

 

接口测试

	/**
	 * 验证码
	 * @param request
	 * @param response
	 * @param session
	 * @throws IOException
	 */
	@RequestMapping("/code.jpg")
	public void getCode3(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
		int width = NumberUtils.toInt(request.getParameter("width"), 100);
		int height = NumberUtils.toInt(request.getParameter("height"), 30);
		int codeCount = NumberUtils.toInt(request.getParameter("codeCount"), 4);
		int lineCount = NumberUtils.toInt(request.getParameter("lineCount"), 10);
		if (width > 1000) width = 100;
		if (height > 300) height = 30;
		if (codeCount > 10) codeCount = 4;
		if (lineCount > 100) lineCount = 10;
		// 设置响应的类型格式为图片格式
		response.setContentType("image/jpeg");
		// 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// 自定义参数
		CaptchaUtil code = new CaptchaUtil(width, height, codeCount, lineCount);
        
                // 放入redis做校验
		String sessionId = session.getId();
		RedisUtil.set("captcha_" + sessionId, code.getCode(), 60 * 30);

                // 写出到前端
		code.write(response.getOutputStream());

	}

 

### Java 图形验证码实现 #### 自定义图形验证码工具类 对于不想引入额外依赖的情况,可以选择编写自己的图形验证码工具类。此类能够满足基本需求并提供一定的灵活性。 ```java import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.util.Random; public class CustomCaptchaGenerator { private static final int WIDTH = 100; // 验证码图片宽度 private static final int HEIGHT = 40; // 验证码图片高度 private static final char[] CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray(); public static BufferedImage createImage(String text) { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); // 设置背景颜色 g.setColor(getRandomColor(200, 250)); g.fillRect(0, 0, WIDTH, HEIGHT); // 绘制干扰线 drawDisturbLines(g, random); // 设置字体样式 Font font = new Font("Arial", Font.BOLD | Font.ITALIC, 24); g.setFont(font); // 将字符绘制到图像上 for (int i = 0; i < text.length(); ++i) { g.setColor(new Color(random.nextInt(101), random.nextInt(101), random.nextInt(101))); g.drawString(text.substring(i, i + 1), 20 * i + 10, 25); } g.dispose(); return image; } private static void drawDisturbLines(Graphics g, Random r) { g.setColor(Color.BLACK); for(int i=0;i<5;++i){ int x=r.nextInt(WIDTH); int y=r.nextInt(HEIGHT); int xl=r.nextInt(12); int yl=r.nextInt(12); g.drawLine(x,y,x+xl,y+yl); } } private static Color getRandomColor(int fc,int bc){ Random random=new Random(); if(fc>255)fc=255; if(bc>255)bc=255; int r=fc+random.nextInt(bc-fc); int g=fc+random.nextInt(bc-fc); int b=fc+random.nextInt(bc-fc); return new Color(r,g,b); } } ``` 此代码片段展示了如何创建一个简单的图形验证码生成器[^1]。 #### 使用第三方库 EasyCaptcha 如果希望减少开发工作量,则可以考虑采用成熟的第三方库来处理图形验证码逻辑。`EasyCaptcha` 提供了丰富的特性和良好的易用性: - 支持多种类型的验证码(如 GIF 动画、中文文字等) - 可定制化设置,比如调整尺寸、改变字符集等 - 方便集成至 Spring Boot 或其他框架内应用 - 内置安全特性增强机制,例如添加贝塞尔曲线作为干扰线条 安装 `EasyCaptcha` 后,在项目中可以通过如下方式快速构建验证码实例: ```xml <!-- Maven Dependency --> <dependency> <groupId>com.github.whvcse</groupId> <artifactId>easycaptcha-core</artifactId> <version>最新版本号</version> </dependency> ``` ```java // 创建默认规格的纯文本验证码对象 DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.textproducer.char.string","0123456789"); defaultKaptcha.setConfig(new Config(properties)); String captchaText = defaultKaptcha.createTextCaptha(); BufferedImage bufferedImage = defaultKaptcha.createImage(captchaText); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage,"jpg",outputStream); byte[] bytes = outputStream.toByteArray(); ``` 上述例子说明了通过 `EasyCaptcha` 如何便捷地生产带有随机字符串的静态图形式样的验证码[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值