圖片數字驗證碼
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;
/**
* 驗證碼圖片生成類
* @author Administrator
*
*/
public class CaptchaUtil {
private static final Logger LOGGER = Logger.getLogger(CaptchaUtil.class);
// 隨機產生的字串
private static final String RANDOM_STRS = "0123456789";
private static final String FONT_NAME = "Fixedsys";
private static final int FONT_SIZE = 18;
private Random random = new Random();
private int width = 80;// 圖片寬
private int height = 25;// 圖片高
private int lineNum = 50;// 干擾線數量
private int strNum = 4;// 隨機產生字元數量
/**
* 生成隨機圖片
*/
public BufferedImage genRandomCodeImage(StringBuffer randomCode) {
// BufferedImage類是具有緩衝區的Image類
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_BGR);
// 獲取Graphics物件,便於對影象進行各種繪製操作
Graphics g = image.getGraphics();
// 設定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 設定干擾線的顏色
g.setColor(getRandColor(110, 120));
// 繪製干擾線
for (int i = 0; i <= lineNum; i++) {
drowLine(g);
}
// 繪製隨機字元
g.setFont(new Font(FONT_NAME, Font.ROMAN_BASELINE, FONT_SIZE));
for (int i = 1; i <= strNum; i++) {
randomCode.append(drowString(g, i));
}
g.dispose();
return image;
}
/**
* 給定範圍獲得隨機顏色
*/
private Color getRandColor(int fc, int bc) {
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);
}
/**
* 繪製字串
*/
private String drowString(Graphics g, int i) {
g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
.nextInt(121)));
String rand = String.valueOf(getRandomString(random.nextInt(RANDOM_STRS
.length())));
g.translate(random.nextInt(3), random.nextInt(3));
g.drawString(rand, 13 * i, 16);
return rand;
}
/**
* 繪製干擾線
*/
private void drowLine(Graphics g) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int x0 = random.nextInt(16);
int y0 = random.nextInt(16);
g.drawLine(x, y, x + x0, y + y0);
}
/**
* 獲取隨機的字元
*/
private String getRandomString(int num) {
return String.valueOf(RANDOM_STRS.charAt(num));
}
public static void main(String[] args) {
CaptchaUtil tool = new CaptchaUtil();
StringBuffer code = new StringBuffer();
BufferedImage image = tool.genRandomCodeImage(code);
System.out.println(">>> random code =: " + code);
try {
// 將記憶體中的圖片通過流動形式輸出到客戶端
ImageIO.write(image, "JPEG", new FileOutputStream(new File(
"random-code.jpg")));
} catch (Exception e) {
LOGGER.info("context", e);
}
}
}