登錄、註冊的驗證碼

在登錄或註冊網站時,相信大家都會遇到填寫驗證碼的問題,那麼到底爲什麼要有驗證碼的存在呢?原因是爲了防止個別不法分子利用程序來進行惡意註冊,破壞網站的服務器,那麼這些驗證碼是怎麼用代碼寫的呢,現在我就把這些代碼貼出來跟大家分享一下

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode {
	//確定寬高
	private int width = 70;
	private int height =40;
	private Random random = new Random();
	//設置可供選擇的字體
	private String[] font = {"宋體", "華文楷體", "黑體", "微軟雅黑", "楷體_GB2312"};
	//設置可供選擇的的字符
	private String code = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
	//設置背景顏色爲白色
	Color bgColor = new Color(255,255,255);
	//設置返回圖片字符的String
	private String text;
	
	//設置隨機顏色
	private Color randomColor(){
		int red = random.nextInt(150);
		int green = random.nextInt(150);
		int blue = random.nextInt(150);
		return new Color(red,green,blue);	
	}
	
	//設置字體的隨機樣式
	private Font randomFont(){
		int index = random.nextInt(font.length);
		int style = random.nextInt(4);
		int size = random.nextInt(4)+ 25;
		return new Font(font[index],style,size);
	}
	
	//設置隨機字符
	private char randomChar(){
		int index = random.nextInt(code.length());
		return code.charAt(index);
	}
	
	//設置干擾線
	private void drawLine(BufferedImage bi){
		int num = 3;//畫三條線
		Graphics2D g = (Graphics2D)bi.getGraphics();
		g.setColor(Color.blue);
		for (int index = 0;index < num;index++){
			int x1 = random.nextInt(width);
			int y1 = random.nextInt(height);
			int x2 = random.nextInt(width);
			int y2 = random.nextInt(height);
			g.setStroke(new BasicStroke(1.5F));//設置干擾線輪廓
			g.drawLine(x1, y1, x2, y2);
	}
}
	
	//創建BufferdImage,設置其背景色和邊框
	private BufferedImage createImage(){
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = (Graphics2D)bi.getGraphics();
		g.setColor(bgColor);
		g.fillRect(0, 0, width, height);
		g.setColor(Color.gray);
		g.drawRect(0, 0, width - 1, height - 1);
		return bi;
	}
	
	//調用這個方法得到驗證碼
	 public BufferedImage getImage(){ 
		 int num = 4;//設置驗證碼的個數爲4個
		 StringBuffer sb = new StringBuffer();
		 BufferedImage bi = createImage();
		 Graphics2D g = (Graphics2D)bi.getGraphics();
		 for (int index = 0;index < num;index++){
			 String str = randomChar() + "";
			 sb.append(str);
			 float x = index * 1.0F * width / 4;
			 g.setColor(randomColor());
			 g.setFont(randomFont());
			 g.drawString(str, x, height - 5);
		 }
		 this.text = sb.toString();
		 drawLine(bi);
		 return bi;
	 }
	 
		// 返回驗證碼圖片上的文本
		public String getText () {
			return text;
		}
		
		// 保存圖片到指定的輸出流
		public static void output (BufferedImage image, OutputStream out) 
					throws IOException {
			ImageIO.write(image, "JPEG", out);
		}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章