1. 程式人生 > >圖片驗證碼(Struts2中使用)

圖片驗證碼(Struts2中使用)

五個 [] ext.get 圖片 發送請求 pan 畫筆 資源 contex

寫在前面:

  最近在項目中做了一個登錄頁面,用到了圖片驗證碼的功能,所以記錄一下。方便之後再有用到,直接拿來用即可。其實圖片驗證碼的生成都是有固定步驟的,網上也有很多的例子,有的時候,如果不想深究,都是可以直接拿來用的。嘻嘻~~~~

生成圖片驗證碼工具類並在struts2中使用,大概需要以下五個步驟:

1.獲取隨機數驗證碼字符串
2.生成驗證碼圖片
3.將圖片轉為圖片流格式
4.提供圖片流類型的get()方法

5.配置struts.xml

其實上面的前三個步驟,都是在為生成圖片驗證碼做準備,我們將前三步的內容,封裝成一個圖片驗證碼工具類。

圖片驗證碼工具類:
/**
 * Description:生成圖片驗證碼工具類
 *           1.獲取隨機數驗證碼字符串
 *           2.生成驗證碼圖片
 *           3.將圖片轉為圖片流格式
 * Author: Eleven
 * Date: 2017/12/16 8:35
 
*/ public class CodeUtil { //1.生成隨機數驗證碼字符串 public static String getCodeStr(){ //字符數組(除去易混淆的數字0、數字1、字母l、字母o、字母O) char[] codes = "23456789ABCDEFGHIJKMNPQRSTUVWXYZ".toCharArray(); //指定驗證碼長度 int len = 4; //生成隨機的驗證碼字符串 String code = ""; for(int
i=0;i<len;i++){ int r = (int) (Math.random()*codes.length); code += String.valueOf(codes[r]); } System.out.println("驗證碼字符串"+code); return code; } /** *生成驗證碼圖片 * @param codeStr 驗證碼字符串 * @return 圖片 */ public static BufferedImage createImage(String codeStr){
//驗證碼長度 int len = codeStr.length(); //字體大小 int fSize = 20; int fWidth = fSize + 1; //圖片寬度 int width = fWidth * len + 6; //圖片高度 int height = fSize * 2 + 1; //圖片 BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB ); //獲取畫筆 Graphics g = img.getGraphics(); //設置背景顏色 並填充 g.setColor(new Color(0xDCDCDC)); g.fillRect(0,0,width,height); //設置邊框顏色 g.setColor(Color.LIGHT_GRAY); g.drawRect(0,0,width-1,height-1); //繪制小點點 1*1的小矩形 g.setColor(Color.LIGHT_GRAY); Random random = new Random(); for(int i=0;i<len*6;i++){ int x = random.nextInt(width); int y = random.nextInt(height); //1*1的小矩形 g.drawRect(x,y,1,1); } //或者填充100條幹擾線 /* for (int i = 0; i < 100; i++) { g.setColor(getRandColor(160, 200)); g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); }*/ //繪制驗證碼 int codeY = height - 10; //g.setColor(new Color(19,148,246)); //設置字體 g.setFont(new Font(null, Font.BOLD, fSize)); for(int i=0;i<len;i++){ //設置隨機顏色 g.setColor(new Color(random.nextInt(150), random.nextInt(150), random.nextInt(150))); g.drawString(String.valueOf(codeStr.charAt(i)),i * 17 + 9, codeY); } //關閉資源 g.dispose(); return img; } /** * 驗證碼圖片轉為流格式 * @param img 圖片 * @return 圖片流 */ public static ByteArrayInputStream getImgAsInputStream(BufferedImage img){ ByteArrayInputStream inputStream = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos); try { jpeg.encode(img); byte[] bts = bos.toByteArray(); inputStream = new ByteArrayInputStream(bts); } catch (IOException e) { e.printStackTrace(); throw new BusinessException("圖片轉為圖片流格式異常了呀"); } return inputStream; } //填充幹擾線的時候生成隨機顏色 public static 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); } }

工具類已經寫好了(前三個步驟已經做完了),在action中進行調用(記得第四步的提供圖片流的get()方法)

action類:

/**
 * Description:登錄Action
 * Author: Eleven
 * Date: 2017/12/14 19:28
 */
@Controller("LoginAction")
public class LoginAction2 extends BaseAction{

    //圖片流
    private ByteArrayInputStream inputStream;

    public String getCode(){
        //利用驗證碼工具類生成圖片驗證碼
        //1.獲取隨機數驗證碼字符串
        String code = CodeUtil.getCodeStr();
        //2.生成驗證碼圖片
        BufferedImage image = CodeUtil.createImage(code);
        //3.將圖片轉為圖片流格式
        inputStream = CodeUtil.getImgAsInputStream(image);
        //獲取驗證碼字符串存到session中
        ActionContext.getContext().getSession().put("code", code);

        return SUCCESS;
    }


   //4.提供圖片流的get()方法
    public ByteArrayInputStream getInputStream() {
        return inputStream;
    }
}

完成第5步,配置struts.xml文件:

 <!--驗證碼-->
        <action name="getCode" class="LoginAction" method="getCode">
            <result type="stream">
                <param name="contentType">image/jpeg</param>
                <!--與action中提供get方法的變量名相同-->
                <param name="inputName">inputStream</param>
            </result>
        </action>

經過上面的幾個步驟,就已經大功告成了,下面我們在jsp頁面進行調用:

<img id="codeImg" src="getCode" name="codeImg" height="25px" width="70px" alt="看不清,換一張" onclick="changeCode()">

src是調用獲取驗證碼的action,可以點擊圖片進行更換驗證碼,調用的js如下:

<script type="text/javascript">
  function changeCode(){
       //加一個時間戳,防止瀏覽器不重新發送請求就直接使用緩存中的圖片,而導致點擊時不進行刷新
            document.form1.codeImg.src = "${baseURL}/getCode.action?timeStamp=" + new Date().getTime();

        }
</script>

成功截圖:
技術分享圖片小小迷你圖,啊哈哈哈~~~~~真可愛。。。。。。




參考鏈接:http://www.cnblogs.com/dongliyang/archive/2012/08/24/2654431.html



圖片驗證碼(Struts2中使用)