验证码加减法

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 *<p>Title:VerificationCode.java</p>
 *<p>Description:验证码工具类</p>
 */
public class VerificationCode {
    private static final Logger LOG = LoggerFactory.getLogger(VerificationCode.class);
    
    private static final int IMG_WIDTH=118;  
    private static final int IMG_HEIGHT=45;  
    private int result;  
    private String[] str = {"+", "-"};
     
    public BufferedImage drawVerificationCodeImage(){  
		// 在内存中创建图象
		BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
		// g.setFont(new Font("Times New Roman", Font.TYPE1_FONT, 29));
		g.setColor(getRandColor(160, 200));

		for (int i = 0; i < 150; i++) {
			int x = random.nextInt(IMG_WIDTH);
			int y = random.nextInt(IMG_HEIGHT);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}
		// 画边框
		g.setColor(new Color(50, 143, 207));
		g.drawRect(0, 0, IMG_WIDTH - 1, IMG_HEIGHT - 1);
		// 取随机产生的认证码(2位数字)
		char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8','9' };
		// 创建集合存放生成的两个数字
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < 2; i++) {
			String rand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
			list.add(rand);
		}
		
		if(StringUtils.equals("+", str[new Random().nextInt(2)])){
			// 先取出来两个数字的和,然后再给list集合添加“+”和“=”以便组成加法算式
			result = Integer.parseInt(list.get(0)) + Integer.parseInt(list.get(1));
			LOG.debug("生成的验证码为:" + list.get(0) + "+" + list.get(1) + "=");
			list.add(1, "+");
		}else {
			result = Integer.parseInt(list.get(0)) - Integer.parseInt(list.get(1));
			LOG.debug("生成的验证码为:" + list.get(0) + "-" + list.get(1) + "=");
			list.add(1, "-");
		}
		LOG.debug("num = "+result);
		list.add(3, "=");
		list.add(4, "?");
		
		Map<Integer, Font> fontmap = createFont();
		// 遍历集合list将加法算是生成图片
		for (int j = 0; j < list.size(); j++) {
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
			//随机一种字体
			g.setFont(fontmap.get((int) (Math.random() * fontmap.size())));
			g.drawString(list.get(j) + "  ", 13 * j + 6, 30);
		}
		// 图象生效
		g.dispose();
		return image;
    }  
    
	/*
	 * 给定范围获得随机颜色
	 */
	private 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);
	}
    
	/**
	 * 生成随机字体
	 * @return
	 */
	public static Map<Integer,Font> createFont(){
		Map<Integer,Font>  result=new HashMap<Integer,Font>();
		Font font1=new Font("Dialog", Font.BOLD, 19+(int)(Math.random()*16));
		Font font2=new Font("Dialog", Font.ITALIC, 19+(int)(Math.random()*16));
		Font font3=new Font("Dialog", Font.PLAIN, 19+(int)(Math.random()*16));
		Font font4=new Font("DialogInput", Font.BOLD, 19+(int)(Math.random()*16));
		Font font5=new Font("DialogInput", Font.ITALIC, 19+(int)(Math.random()*16));
		Font font6=new Font("DialogInput", Font.PLAIN, 19+(int)(Math.random()*16));
		Font font7=new Font("Monospaced", Font.BOLD, 19+(int)(Math.random()*16));
		Font font8=new Font("Monospaced", Font.ITALIC, 19+(int)(Math.random()*16));
		Font font9=new Font("Monospaced", Font.PLAIN, 19+(int)(Math.random()*16));
		Font font10=new Font("SansSerif", Font.BOLD, 19+(int)(Math.random()*16));
		Font font11=new Font("SansSerif", Font.ITALIC, 19+(int)(Math.random()*16));
		Font font12=new Font("SansSerif", Font.PLAIN, 19+(int)(Math.random()*16));
		Font font13=new Font("Times New Roman", Font.BOLD, 19+(int)(Math.random()*16));
		Font font14=new Font("Times New Roman", Font.ITALIC, 19+(int)(Math.random()*16));
		Font font15=new Font("Times New Roman", Font.PLAIN, 19+(int)(Math.random()*16));
		Font font16=new Font("arial", Font.BOLD, 19+(int)(Math.random()*16));
		Font font17=new Font("arial", Font.ITALIC, 19+(int)(Math.random()*16));
		Font font18=new Font("arial", Font.PLAIN, 19+(int)(Math.random()*16));
		result.put(1, font1);result.put(2, font2);result.put(3, font3);result.put(4, font4);
		result.put(5, font5);result.put(6, font6);result.put(7, font7);result.put(8, font8);
		result.put(9, font9);result.put(10, font10);result.put(11, font11);result.put(12, font12);
		result.put(13, font13);result.put(14, font14);result.put(15, font15);result.put(16, font16);
		result.put(17, font17);result.put(18, font18);
		return result;
	}
    
    public int getXyresult() {  
        return result;  
    }  
}


@Controller
@RequestMapping("/code")
public class CheckCodeController extends BaseController{

	@RequestMapping
	public void generate(HttpServletResponse response){
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String code = drawImg(output);

		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		session.setAttribute(Const.SESSION_PIC_CODE, code);

		try {
			ServletOutputStream out = response.getOutputStream();
			output.writeTo(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String drawImg(ByteArrayOutputStream output){
		try {
			VerificationCode code = new VerificationCode();
			BufferedImage img = code.drawVerificationCodeImage();
			ImageIO.write(img, "jpg", output);
			
			return StringUtil.toTrim(code.getXyresult());
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		} 
		
	}
	
}

 

转载于:https://my.oschina.net/chaun/blog/788624

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值