JAVA 生成文字图像验证码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33335577/article/details/81739888

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

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;

public class YZM {

	private static String chars = "一二三四五六七八九十";

	private static String path = "D:\\img\\";

	public static void main(String[] args) throws IOException {
		//设置保存本地位置
		File file = new File(path + "123.jpg");
		//WEB响应验证码使用,HttpServletResponse.getOutputStream()。获取流对象
		System.out.println(new YZM().imageCode(new FileImageOutputStream(file)));
	}

	/**
	 * 生成验证码
	 * 
	 * @return
	 * @throws IOException
	 */
	public boolean imageCode(ImageOutputStream responseOutputStream) throws IOException {
		// 在内存中创建图象
		int width = 180, height = 50,size = 40;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		Graphics g = image.getGraphics();
		// 生成随机类
		Random random = new Random();
		// 设定背景色
		g.setColor(getRandColor(230, 255));
		g.fillRect(0, 0, width, height);
		// 设定字体
		g.setFont(new Font("宋体", Font.CENTER_BASELINE | Font.ITALIC, size));
		// 产生0条干扰线,
		g.drawLine(0, 0, 0, 0);
		// 取随机产生的认证码(4位数字)
		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = chars.charAt(random.nextInt(chars.length())) + "";
			sRand += rand;
			// 将认证码显示到图象中
			g.setColor(getRandColor(100, 150));
			g.drawString(rand, size * i + 10, size);
		}
		System.out.println("答案:" + sRand);
		//生成干扰线
		for (int i = 0; i < (random.nextInt(5)+5); i++) {
			g.setColor(new Color(random.nextInt(255) + 1, random.nextInt(255) + 1, random.nextInt(255) + 1));
			g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
		}
		// 图象生效
		g.dispose();
		// 输出图象到页面
		ImageIO.write(image, "JPEG", responseOutputStream);
		// 以下关闭输入流!
		responseOutputStream.flush();
		responseOutputStream.close();
		// 获得页面key值
		return true;
	}

	/**
	 * 给定范围获得随机颜色
	 * 
	 * @param fc
	 * @param bc
	 * @return
	 */
	Color getRandColor(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);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_33335577/article/details/81739888