验证码工具类【复制】

public class getRandomPictrue extends BaseAction implements IgnoreAction {
	
	private ByteArrayInputStream image;// 图像  
    private String str;// 验证码  
    private static final int WIDTH = 80;  
    private static final int HEIGHT = 20;
	/**
	 * 
	 */
	private static final long serialVersionUID = -6098322779401546263L;

	public String getRandomPictrue() {  
		int width = 120;  
        int height = 30;
        
     // 步骤一 绘制一张内存中图片  
        BufferedImage bufferedImage = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_RGB);
        
     // 步骤二 图片绘制背景颜色 ---通过绘图对象  
        Graphics graphics = bufferedImage.getGraphics();// 得到画图对象 --- 画笔
        
     // 绘制任何图形之前 都必须指定一个颜色  
        graphics.setColor(getRandColor(200, 250));  
        graphics.fillRect(0, 0, width, height);   
     // 步骤三 绘制边框  
        graphics.setColor(Color.WHITE);  
        graphics.drawRect(0, 0, width - 1, height - 1);
     // 步骤四 四个随机数字  
        Graphics2D graphics2d = (Graphics2D) graphics;     
      
     // 设置输出字体  
        graphics2d.setFont(new Font("宋体", Font.BOLD, 18));  
     
        String words ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        //String words ="1234567890";
        Random random = new Random();// 生成随机数
        
     // 定义StringBuffer   
        StringBuffer sb = new StringBuffer();
     // 定义x坐标  
        int x = 10;    
       
        for (int i = 0; i < 4; i++) {  
            // 随机颜色  
            graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random  
                    .nextInt(110), 20 + random.nextInt(110)));  
            // 旋转 -30 --- 30度  
            int jiaodu = random.nextInt(60) - 30;  
            // 换算弧度  
            double theta = jiaodu * Math.PI / 180;  
 
            // 生成一个随机数字  
            int index = random.nextInt(words.length()); // 生成随机数 0 到 length - 1  
            // 获得字母数字  
            char c = words.charAt(index);  
            sb.append(c);  
            // 将c 输出到图片  
            graphics2d.rotate(theta, x, 20);  
            graphics2d.drawString(String.valueOf(c), x, 20);  
            graphics2d.rotate(-theta, x, 20);  
            x += 30;  
        }  
        
     // 将生成的字母存入到session中  
        ServletActionContext.getRequest().getSession().setAttribute("checkcode", sb.toString());
        
     // 步骤五 绘制干扰线  
        graphics.setColor(getRandColor(160, 200));  
        int x1;  
        int x2;  
        int y1;  
        int y2;  
        for (int i = 0; i < 30; i++) {  
            x1 = random.nextInt(width);  
            x2 = random.nextInt(12);  
            y1 = random.nextInt(height);  
            y2 = random.nextInt(12);  
            graphics.drawLine(x1, y1, x1 + x2, x2 + y2);  
        }    
        
     // 将上面图片输出到浏览器 ImageIO  
        graphics.dispose();// 释放资源  
        try {
			ImageIO.write(bufferedImage, "jpg", ServletActionContext.getResponse().getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        return NONE;
	}
	/** 
     * 功能:设置第一种验证码的属性 
     */  
    public void initNumVerificationCode(BufferedImage image) {  
  
        Random random = new Random(); // 生成随机类  
        Graphics g = initImage(image, random);  
        String sRand = "";  
        for (int i = 0; i < 4; i++) {  
            String rand = String.valueOf(random.nextInt(10));  
            sRand += rand;  
            // 将认证码显示到图象中  
            g.setColor(new Color(20 + random.nextInt(110), 20 + random  
                    .nextInt(110), 20 + random.nextInt(110)));  
            // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成  
            g.drawString(rand, 13 * i + 6, 16);  
        }  
        this.setStr(sRand);/* 赋值验证码 */  
        // 图象生效  
        g.dispose();  
        this.setImage(drawImage(image));  
    }  
    /** 
     * 功能:设置第二种验证码属性 
     */  
    public void initLetterAndNumVerificationCode(BufferedImage image) {  
  
        Random random = new Random(); // 生成随机类  
        Graphics g = initImage(image, random);  
        String[] letter = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",  
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",  
                "W", "X", "Y", "Z" };  
        String sRand = "";  
        for (int i = 0; i < 4; i++) {  
            String tempRand = "";  
            if (random.nextBoolean()) {  
                tempRand = String.valueOf(random.nextInt(10));  
            } else {  
                tempRand = letter[random.nextInt(25)];  
                if (random.nextBoolean()) {// 随机将该字母变成小写  
                    tempRand = tempRand.toLowerCase();  
                }  
            }  
            sRand += tempRand;  
            g.setColor(new Color(20 + random.nextInt(10), 20 + random  
                    .nextInt(110), 20 + random.nextInt(110)));  
            g.drawString(tempRand, 13 * i + 6, 16);  
        }  
        this.setStr(sRand);/* 赋值验证码 */  
        g.dispose(); // 图象生效  
        this.setImage(drawImage(image));  
    }  
  
    /** 
     * 功能:设置第三种验证码属性 即:肆+?=24 
     */  
    public void initChinesePlusNumVerificationCode(BufferedImage image) {  
        String[] cn = { "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾" };  
        Random random = new Random(); // 生成随机类  
        Graphics g = initImage(image, random);  
        int x = random.nextInt(10) + 1;  
        int y = random.nextInt(30);  
        this.setStr(String.valueOf(y));  
        g.setFont(new Font("楷体", Font.PLAIN, 14));// 设定字体  
        g.setColor(new Color(20 + random.nextInt(10), 20 + random.nextInt(110),  
                20 + random.nextInt(110)));  
        g.drawString(cn[x - 1], 1 * 1 + 6, 16);  
        g.drawString("+", 22, 16);  
        g.drawString("?", 35, 16);  
        g.drawString("=", 48, 16);  
        g.drawString(String.valueOf(x + y), 61, 16);  
        g.dispose(); // 图象生效  
        this.setImage(drawImage(image));  
  
    }  
  
    public Graphics initImage(BufferedImage image, Random random) {  
        Graphics g = image.getGraphics(); // 获取图形上下文  
        g.setColor(getRandColor(200, 250));// 设定背景色  
        g.fillRect(0, 0, WIDTH, HEIGHT);  
        g.setFont(new Font("Times New Roman", Font.PLAIN, 14));// 设定字体  
        g.setColor(getRandColor(160, 200)); // 随机产生165条干扰线,使图象中的认证码不易被其它程序探测到  
        for (int i = 0; i < 165; i++) {  
            int x = random.nextInt(WIDTH);  
            int y = random.nextInt(HEIGHT);  
            int xl = random.nextInt(12);  
            int yl = random.nextInt(12);  
            g.drawLine(x, y, x + xl, y + yl);  
        }  
        return g;  
    }  
  
    public ByteArrayInputStream drawImage(BufferedImage image) {  
        ByteArrayInputStream input = null;  
        ByteArrayOutputStream output = new ByteArrayOutputStream();  
        try {  
            ImageOutputStream imageOut = ImageIO  
                    .createImageOutputStream(output);  
            ImageIO.write(image, "JPEG", imageOut);  
            imageOut.close();  
            input = new ByteArrayInputStream(output.toByteArray());  
        } catch (Exception e) {  
            System.out.println("验证码图片产生出现错误:" + e.toString());  
        }  
        return input;  
    }  
  
    /* 
     * 功能:给定范围获得随机颜色 
     */  
    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 String getVerificationCodeValue() {  
        return this.getStr();  
    }  
  
    /** 
     * 功能:取得验证码图片 
     *  
     * @return 
     */  
    public ByteArrayInputStream getImage() {  
        return this.image;  
    }  
  
    public String getStr() {  
        return str;  
    }  
  
    public void setStr(String str) {  
        this.str = str;  
    }  
  
    public void setImage(ByteArrayInputStream image) {  
        this.image = image;  
    } 
    
    private void mian() {
		// TODO Auto-generated method stub
    	System.out.println(getRandomPictrue());
	}
}

猜你喜欢

转载自www.cnblogs.com/hmhhz/p/12689479.html
今日推荐