动态验证码制作(RandomCodeImage )

在很多的网页中,他们的登录,注册等等地方都有验证码的存在,这下验证码都是动态生成的,有些验证码模糊不堪,有些干扰很多,

而验证码是用来干什么的呢?防止人为输入的不安全?错,验证码真正的用途在于,防止机器的识别,所以,验证码往往都是图片格式的,

人可以识别出来,而机器就识别不出来,这样就可以防止机器识别,就可以保证正在操作的是人,而并不是机器的操作,安全性更高;

下面就分享一下我自己写得一个简单的验证码制作的代码!希望可以一起学习,有什么不足,敬请指正;

这是我封装的一个验证码制作的java类;

copy源代码:

package com.cj.test;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.servlet.ServletOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class RandomCodeImage {
    
    public static BufferedImage drawRandomCode(int width,int height,int fontNum){   //调用时只需要传入三个参数,宽.高,字符数;
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2d=(Graphics2D)bufferedImage.getGraphics();
        Color color=new Color((int)(Math.random()*35)+219,
                (int)(Math.random()*35)+219,(int)(Math.random()*35)+219);
        graphics2d.setBackground(color);
        graphics2d.clearRect(0, 0, width, height);
        
        //产生随机的颜色分量来构造颜色值,输出的字符的颜色值都将不同;
        Color fColor=new Color((int)(Math.random()*71)+55,
                (int)(Math.random()*71)+55,(int)(Math.random()*71)+55);
        
        
        //画边框
        graphics2d.setColor(Color.black);
        graphics2d.drawRect(0, 0, width-1, height-1);
                
        
        graphics2d.setColor(fColor);
        
        //设置字体,字体的大小应该根据图片的高度来定
        graphics2d.setFont(new Font("Times new Roman",Font.BOLD, height-20));
        
        
        //randomCode用于保存随机产生的验证码,以便于用户登录后进行验证
        StringBuffer randomCode=new StringBuffer();
        
        //随机产生的文字输出Y坐标,也跟高度有关系
        int sp=(int)(Math.random()*(height-23))+22;
        for (int i = 0; i < fontNum; i++) {
            //随机产生的4位验证码字符
            char strRand=(char)(Math.random()>0.50?(int)(Math.random()*9)+48
                    :(int)(Math.random()*25)+97);
            //用随机产生的颜色将验证码绘制到图像中。
            graphics2d.drawString(String.valueOf(strRand), 24*i+12
                    , sp+(int)(Math.random()*5));
            //将4个随机产生的数组合到一起
            randomCode.append(strRand);
            
        }

    //  随机生成几条干扰线条,最少2条,最多5条;
        for (int i = 1; i < (int)(Math.random()*3)+3; i++) {
            graphics2d.drawLine(0,sp-(int)(Math.random()*20),width
                    ,sp-(int)(Math.random()*20));
        }
        return bufferedImage;
    }
}

在Servlet中调用时代码例子:

//将图像输出到Servlet输出流中;
        ServletOutputStream sos=response.getOutputStream();
        JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(sos);
        encoder.encode(RandomCodeImage.drawRandomCode(130, 50, 5));

原文地址:https://www.cnblogs.com/cj28-27/p/5596542.html