在很多的網頁中,他們的登錄,注冊等等地方都有驗證碼的存在,這下驗證碼都是動態生成的,有些驗證碼模糊不堪,有些干擾很多,
而驗證碼是用來干什么的呢?防止人為輸入的不安全?錯,驗證碼真正的用途在於,防止機器的識別,所以,驗證碼往往都是圖片格式的,
人可以識別出來,而機器就識別不出來,這樣就可以防止機器識別,就可以保證正在操作的是人,而並不是機器的操作,安全性更高;
下面就分享一下我自己寫得一個簡單的驗證碼制作的代碼!希望可以一起學習,有什么不足,敬請指正;
這是我封裝的一個驗證碼制作的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));