java實現限制驗證碼次數登錄

package com.spring.controller;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class VerifyCodeServlet extends HttpServlet {
// 驗證碼圖片的寬度。
private int width = 60;
// 驗證碼圖片的高度。
private int height = 20;
// 驗證碼字元個數
private int codeCount = 4;
private int x = 0;
// 字體高度
private int fontHeight;
private int codeY;
char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

⑵ spring框架的java登錄驗證碼怎麼寫

可以參考下下面的代碼,這個代碼是servlet生成的,稍微修改下就能用的

packageservlet;

importjava.awt.Color;
importjava.awt.Font;
importjava.awt.Graphics;
importjava.awt.image.BufferedImage;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Random;

importjavax.imageio.ImageIO;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;

{

publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{

BufferedImageimage=newBufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
Graphicsg=image.getGraphics();
Randomr=newRandom();
g.setColor(newColor(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.fillRect(0,0,100,30);
g.setColor(newColor(255,255,255));
g.setFont(newFont(null,Font.BOLD,24));
Stringcode=getCode();
HttpSessionsession=request.getSession();
session.setAttribute("textcode",code);

g.drawString(code,10,25);
response.setContentType("image/jpeg");
OutputStreamos=response.getOutputStream();
ImageIO.write(image,"jpeg",os);
os.close();
}
//隨機生成驗證碼字元串的類
publicstaticStringgetCode(){
char[]letters={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z'};
Stringcode="";
boolean[]bool=newboolean[letters.length];

for(inti=0;i<5;i++){
intnum;
do{
num=(int)(Math.random()*(letters.length));
}while(bool[num]);
code+=letters[num];
bool[num]=true;
}
returncode.toUpperCase();
}

}

⑶ 怎樣用java實現驗證碼

package com.servlet;

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.imageio.ImageIO;

public class PictureCheckCode extends HttpServlet {

private static final long serialVersionUID = 1L;

public PictureCheckCode() {
super();
}

public void destroy() {
super.destroy();
}

public void init() throws ServletException {
super.init();
}
/*該方法主要作用是獲得隨機生成的顏色*/
public Color getRandColor(int s,int e){
Random random=new Random ();
if(s>255) s=255;
if(e>255) e=255;
int r,g,b;
r=s+random.nextInt(e-s); //隨機生成RGB顏色中的r值
g=s+random.nextInt(e-s); //隨機生成RGB顏色中的g值
b=s+random.nextInt(e-s); //隨機生成RGB顏色中的b值
return new Color(r,g,b);
}

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//設置不緩存圖片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
//指定生成的響應圖片,一定不能缺少這句話,否則錯誤.
response.setContentType("image/jpeg");
int width=86,height=22; //指定生成驗證碼的寬度和高度
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //創建BufferedImage對象,其作用相當於一圖片
Graphics g=image.getGraphics(); //創建Graphics對象,其作用相當於畫筆
Graphics2D g2d=(Graphics2D)g; //創建Grapchics2D對象
Random random=new Random();
Font mfont=new Font("楷體",Font.BOLD,16); //定義字體樣式
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height); //繪制背景
g.setFont(mfont); //設置字體
g.setColor(getRandColor(180,200));

//繪制100條顏色和位置全部為隨機產生的線條,該線條為2f
for(int i=0;i<100;i++){
int x=random.nextInt(width-1);
int y=random.nextInt(height-1);
int x1=random.nextInt(6)+1;
int y1=random.nextInt(12)+1;
BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL); //定製線條樣式
Line2D line=new Line2D.Double(x,y,x+x1,y+y1);
g2d.setStroke(bs);
g2d.draw(line); //繪制直線
}
//輸出由英文,數字,和中文隨機組成的驗證文字,具體的組合方式根據生成隨機數確定。
String sRand="";
String ctmp="";
int itmp=0;
//制定輸出的驗證碼為四位
for(int i=0;i<4;i++){
switch(random.nextInt(3)){
case 1: //生成A-Z的字母
itmp=random.nextInt(26)+65;
ctmp=String.valueOf((char)itmp);
break;
case 2: //生成漢字
String[] rBase={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
//生成第一位區碼
int r1=random.nextInt(3)+11;
String str_r1=rBase[r1];
//生成第二位區碼
int r2;
if(r1==13){
r2=random.nextInt(7);
}else{
r2=random.nextInt(16);
}
String str_r2=rBase[r2];
//生成第一位位碼
int r3=random.nextInt(6)+10;
String str_r3=rBase[r3];
//生成第二位位碼
int r4;
if(r3==10){
r4=random.nextInt(15)+1;
}else if(r3==15){
r4=random.nextInt(15);
}else{
r4=random.nextInt(16);
}
String str_r4=rBase[r4];
//將生成的機內碼轉換為漢字
byte[] bytes=new byte[2];
//將生成的區碼保存到位元組數組的第一個元素中
String str_12=str_r1+str_r2;
int tempLow=Integer.parseInt(str_12, 16);
bytes[0]=(byte) tempLow;
//將生成的位碼保存到位元組數組的第二個元素中
String str_34=str_r3+str_r4;
int tempHigh=Integer.parseInt(str_34, 16);
bytes[1]=(byte)tempHigh;
ctmp=new String(bytes);
break;
default:
itmp=random.nextInt(10)+48;
ctmp=String.valueOf((char)itmp);
break;
}
sRand+=ctmp;
Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),random.nextInt(110));
g.setColor(color);
//將生成的隨機數進行隨機縮放並旋轉制定角度 PS.建議不要對文字進行縮放與旋轉,因為這樣圖片可能不正常顯示
/*將文字旋轉制定角度*/
Graphics2D g2d_word=(Graphics2D)g;
AffineTransform trans=new AffineTransform();
trans.rotate((45)*3.14/180,15*i+8,7);
/*縮放文字*/
float scaleSize=random.nextFloat()+0.8f;
if(scaleSize>1f) scaleSize=1f;
trans.scale(scaleSize, scaleSize);
g2d_word.setTransform(trans);
g.drawString(ctmp, 15*i+18, 14);
}
HttpSession session=request.getSession(true);
session.setAttribute("randCheckCode", sRand);
g.dispose(); //釋放g所佔用的系統資源
ImageIO.write(image,"JPEG",response.getOutputStream()); //輸出圖片
}
}

⑷ java如何破解驗證碼實現登陸

登入好破解,無非是生成一個cookie,驗證碼的破解就麻煩了,一兩句話肯定是解釋不了的,不過有識別驗證碼的軟體,有些識別率還是挺高的

⑸ Java簡訊驗證碼功能怎麼實現

實現jiava簡訊驗證碼可以按下面的步奏進行:
1、首先,找到一個支持Java語言的介面簡訊平台。
2、接著下載介面文檔,和自己的開發平台進行對接。
3、注意在對接之前測試一下簡訊的速度,一旦對接好想換就比較麻煩,之前就吃過這個虧,最後有個朋友介紹我去簡訊網。
4、如果要購買的話,一定要多測試幾家。
如果在碰到有疑問的地方一定要和技術或者客服多多溝通。

⑹ 驗證碼怎麼用java代碼實現驗證

package util; import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Random;import javax.imageio.ImageIO; public final class ImageUtil { // 驗證碼字元集 private static final char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; // 字元數量 private static final int SIZE = 4; // 干擾線數量 private static final int LINES = 5; // 寬度 private static final int WIDTH = 80; // 高度 private static final int HEIGHT = 40; // 字體大小 private static final int FONT_SIZE = 30; /** * 生成隨機驗證碼及圖片 * 返回的數組中,第1個值是驗證碼,第2個值是圖片 */ public static Object[] createImage() { StringBuffer sb = new StringBuffer(); // 1.創建空白圖片 BufferedImage image = new BufferedImage( WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); // 2.獲取圖片畫筆 Graphics graphic = image.getGraphics(); // 3.設置畫筆顏色 graphic.setColor(Color.LIGHT_GRAY); // 4.繪制矩形背景 graphic.fillRect(0, 0, WIDTH, HEIGHT); // 5.畫隨機字元 Random ran = new Random(); for (int i = 0; i <SIZE; i++) { // 取隨機字元索引 int n = ran.nextInt(chars.length); // 設置隨機顏色 graphic.setColor(getRandomColor()); // 設置字體大小 graphic.setFont(new Font( null, Font.BOLD + Font.ITALIC, FONT_SIZE)); // 畫字元 graphic.drawString( chars[n] + "", i * WIDTH / SIZE, HEIGHT / 2); // 記錄字元 sb.append(chars[n]); } // 6.畫干擾線 for (int i = 0; i < LINES; i++) { // 設置隨機顏色 graphic.setColor(getRandomColor()); // 隨機畫線 graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), ran.nextInt(WIDTH), ran.nextInt(HEIGHT)); } // 7.返回驗證碼和圖片 return new Object[]{sb.toString(), image}; } /** * 隨機取色 */ public static Color getRandomColor() { Random ran = new Random(); Color color = new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256)); return color; } public static void main(String[] args) throws IOException { Object[] objs = createImage(); BufferedImage image = (BufferedImage) objs[1]; OutputStream os = new FileOutputStream("d:/1.png"); ImageIO.write(image, "jpeg", os); os.close(); } }

⑺ 怎麼用java實現驗證碼

1、網上有JS插件啊,這個用java實現的話還是比較麻煩哦,需要java調用畫圖。我有一個內寫好的容例子,是java和servlet做的。

2、親們,這個驗證碼我做了很久才弄出來的,希望大家別介意我收費哦!

⑻ Java如何實現驗證碼驗證功能

Java如何實現驗證碼驗證功能呢?日常生活中,驗證碼隨處可見,他可以在一定程度上保護賬號安全,那麼他是怎麼實現的呢?

Java實現驗證碼驗證功能其實非常簡單:用到了一個Graphics類在畫板上繪制字母,隨機選取一定數量的字母隨機生成,然後在畫板上隨機生成幾條干擾線。

首先,寫一個驗證碼生成幫助類,用來繪制隨機字母:

  • importjava.awt.Color;

  • importjava.awt.Font;

  • importjava.awt.Graphics;

  • importjava.awt.image.BufferedImage;

  • importjava.io.IOException;

  • importjava.io.OutputStream;

  • importjava.util.Random;

  • importjavax.imageio.ImageIO;

  • publicfinalclassGraphicHelper{

  • /**

  • *以字元串形式返回生成的驗證碼,同時輸出一個圖片

  • *

  • *@paramwidth

  • *圖片的寬度

  • *@paramheight

  • *圖片的高度

  • *@paramimgType

  • *圖片的類型

  • *@paramoutput

  • *圖片的輸出流(圖片將輸出到這個流中)

  • *@return返回所生成的驗證碼(字元串)

  • */

  • publicstaticStringcreate(finalintwidth,finalintheight,finalStringimgType,OutputStreamoutput){

  • StringBuffersb=newStringBuffer();

  • Randomrandom=newRandom();

  • BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

  • Graphicsgraphic=image.getGraphics();

  • graphic.setColor(Color.getColor("F8F8F8"));

  • graphic.fillRect(0,0,width,height);

  • Color[]colors=newColor[]{Color.BLUE,Color.GRAY,Color.GREEN,Color.RED,Color.BLACK,Color.ORANGE,

  • Color.CYAN};

  • //在"畫板"上生成干擾線條(50是線條個數)

  • for(inti=0;i<50;i++){

  • graphic.setColor(colors[random.nextInt(colors.length)]);

  • finalintx=random.nextInt(width);

  • finalinty=random.nextInt(height);

  • finalintw=random.nextInt(20);

  • finalinth=random.nextInt(20);

  • finalintsignA=random.nextBoolean()?1:-1;

  • finalintsignB=random.nextBoolean()?1:-1;

  • graphic.drawLine(x,y,x+w*signA,y+h*signB);

  • }

  • //在"畫板"上繪制字母

  • graphic.setFont(newFont("ComicSansMS",Font.BOLD,30));

  • for(inti=0;i<6;i++){

  • finalinttemp=random.nextInt(26)+97;

  • Strings=String.valueOf((char)temp);

  • sb.append(s);

  • graphic.setColor(colors[random.nextInt(colors.length)]);

  • graphic.drawString(s,i*(width/6),height-(height/3));

  • }

  • graphic.dispose();

  • try{

  • ImageIO.write(image,imgType,output);

  • }catch(IOExceptione){

  • e.printStackTrace();

  • }

  • returnsb.toString();

  • }

  • }

接著,創建一個servlet,用來固定圖片大小,以及處理驗證碼的使用場景,以及捕獲頁面生成的驗證碼(捕獲到的二維碼與用戶輸入的驗證碼一致才能通過)。

  • importjava.io.OutputStream;

  • importjavax.servlet.ServletException;

  • importjavax.servlet.annotation.WebServlet;

  • importjavax.servlet.http.HttpServlet;

  • importjavax.servlet.http.HttpServletRequest;

  • importjavax.servlet.http.HttpServletResponse;

  • importjavax.servlet.http.HttpSession;

  • @WebServlet(urlPatterns="/verify/regist.do")

  • {

  • =3398560501558431737L;

  • @Override

  • protectedvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)

  • throwsServletException,IOException{

  • //獲得當前請求對應的會話對象

  • HttpSessionsession=request.getSession();

  • //從請求中獲得URI(統一資源標識符)

  • Stringuri=request.getRequestURI();

  • System.out.println("hello:"+uri);

  • finalintwidth=180;//圖片寬度

  • finalintheight=40;//圖片高度

  • finalStringimgType="jpeg";//指定圖片格式(不是指MIME類型)

  • finalOutputStreamoutput=response.getOutputStream();//獲得可以向客戶端返回圖片的輸出流

  • //(位元組流)

  • //創建驗證碼圖片並返回圖片上的字元串

  • Stringcode=GraphicHelper.create(width,height,imgType,output);

  • System.out.println("驗證碼內容:"+code);

  • //建立uri和相應的驗證碼的關聯(存儲到當前會話對象的屬性中)

  • session.setAttribute(uri,code);

  • System.out.println(session.getAttribute(uri));

  • }

  • }

接著寫一個html注冊頁面用來檢驗一下:

  • <html>

  • <head>

  • <metacharset="UTF-8">

  • <title>注冊</title>

  • <linkrel="stylesheet"href="styles/general.css">

  • <linkrel="stylesheet"href="styles/cell.css">

  • <linkrel="stylesheet"href="styles/form.css">

  • <scripttype="text/javascript"src="js/ref.js"></script>

  • <styletype="text/css">

  • .logo-container{

  • margin-top:50px;

  • }

  • .logo-containerimg{

  • width:100px;

  • }

  • .message-container{

  • height:80px;

  • }

  • .link-container{

  • height:40px;

  • line-height:40px;

  • }

  • .link-containera{

  • text-decoration:none;

  • }

  • </style>

  • </head>

  • <body>

  • <divclass="containerform-container">

  • <formaction="/wen/regist.do"method="post">

  • <divclass="form"><!--注冊表單開始-->

  • <divclass="form-row">

  • <spanclass="cell-1">

  • <iclass="fafa-user"></i>

  • </span>

  • <spanclass="cell-11"style="text-align:left;">

  • <inputtype="text"name="username"placeholder="請輸入用戶名">

  • </span>

  • </div>

  • <divclass="form-row">

  • <spanclass="cell-1">

  • <iclass="fafa-key"></i>

  • </span>

  • <spanclass="cell-11"style="text-align:left;">

  • <inputtype="password"name="password"placeholder="請輸入密碼">

  • </span>

  • </div>

  • <divclass="form-row">

  • <spanclass="cell-1">

  • <iclass="fafa-keyboard-o"></i>

  • </span>

  • <spanclass="cell-11"style="text-align:left;">

  • <inputtype="password"name="confirm"placeholder="請確認密碼">

  • </span>

  • </div>

  • <divclass="form-row">

  • <spanclass="cell-7">

  • <inputtype="text"name="verifyCode"placeholder="請輸入驗證碼">

  • </span>

  • <spanclass="cell-5"style="text-align:center;">

  • <imgsrc="/demo/verify/regist.do"onclick="myRefersh(this)">

  • </span>

  • </div>

  • <divclass="form-row"style="border:none;">

  • <spanclass="cell-6"style="text-align:left">

  • <inputtype="reset"value="重置">

  • </span>

  • <spanclass="cell-6"style="text-align:right;">

  • <inputtype="submit"value="注冊">

  • </span>

  • </div>

  • </div><!--注冊表單結束-->

  • </form>

  • </div>

  • </body>

  • </html>

效果如下圖:



當點擊刷新頁面的時候,驗證碼也會隨著變化,但我們看不清驗證碼時,只要點擊驗證碼就會刷新,這樣局部的刷新可以用JavaScript來實現。

在<img
src="/demo/verify/regist.do">中,添加一個問號和一串後綴數字,當刷新時讓後綴數字不斷改變,那麼形成的驗證碼也會不斷變化,我們可以採用的一種辦法是後綴數字用date代替,date獲取本機時間,時間是隨時變的,這樣就保證了刷新驗證碼可以隨時變化。

代碼如下:

  • functionmyRefersh(e){

  • constsource=e.src;//獲得原來的src中的內容

  • //console.log("source:"+source);

  • varindex=source.indexOf("?");//從source中尋找?第一次出現的位置(如果不存在則返回-1)

  • //console.log("index:"+index);

  • if(index>-1){//如果找到了?就進入內部

  • vars=source.substring(0,index);//從source中截取index之前的內容(index以及index之後的內容都被舍棄)

  • //console.log("s:"+s);

  • vardate=newDate();//創建一個Date對象的一個實例

  • vartime=date.getTime();//從新創建的Date對象的實例中獲得該時間對應毫秒值

  • e.src=s+"?time="+time;//將加了尾巴的地址重新放入到src上

  • //console.log(e.src);

  • }else{

  • vardate=newDate();

  • e.src=source+"?time="+date.getTime();

  • }

  • }

如回答不詳細可追問

⑼ java 登陸時的驗證碼怎麼做

後台寫一個生成圖片隨機的代碼,生成圖片給前台。切換圖片的時候,使用ajax獲取圖片數據就行。
附上生成圖片的代碼
public class ValidateCode {

private int width=180;
private int height=60;
private int codeCount = 4;
private int x = 0;
private int codeY;
private String Code;
private BufferedImage buffImg;
static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private int fontHeight;

public ValidateCode() {
x = width / (codeCount + 2);
fontHeight = height - 2;
codeY = height - 4;
CreateCode();
}

public void CreateCode(){

// 定義圖像buffer
BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 創建一個隨機數生成器類
Random random = new Random();

// 將圖像填充為白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);

// 創建字體,字體的大小應該根據圖片的高度來定。
Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
// 設置字體。
g.setFont(font);

// 畫邊框。
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);

// randomCode用於保存隨機產生的驗證碼,以便用戶登錄後進行驗證。
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;

// 隨機產生codeCount數字的驗證碼。
for (int i = 0; i < codeCount; i++) {
// 得到隨機產生的驗證碼數字。
String strRand = String.valueOf(codeSequence[random.nextInt(62)]);
// 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色值都將不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);

// 用隨機產生的顏色將驗證碼繪制到圖像中。
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i ) * x+20, codeY);

// 將產生的四個隨機數組合在一起。
randomCode.append(strRand);
}
this.Code=randomCode.toString().toUpperCase();
this.buffImg=buffImg;

}

public String getCode() {
return Code;
}

public void setCode(String code) {
Code = code;
}

public BufferedImage getBuffImg() {
return buffImg;
}

public void setBuffImg(BufferedImage buffImg) {
this.buffImg = buffImg;
}
}

⑽ 怎麼用Java代碼實現一個驗證碼,求具體實現方法

packageutil;

importjava.awt.Color;
importjava.awt.Font;
importjava.awt.Graphics;
importjava.awt.image.BufferedImage;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Random;
importjavax.imageio.ImageIO;

publicfinalclassImageUtil{

//驗證碼字元集
privatestaticfinalchar[]chars={
'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
'O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z'};
//字元數量
privatestaticfinalintSIZE=4;
//干擾線數量
privatestaticfinalintLINES=5;
//寬度
privatestaticfinalintWIDTH=80;
//高度
privatestaticfinalintHEIGHT=40;
//字體大小
privatestaticfinalintFONT_SIZE=30;

/**
*生成隨機驗證碼及圖片
*返回的數組中,第1個值是驗證碼,第2個值是圖片
*/
publicstaticObject[]createImage(){
StringBuffersb=newStringBuffer();
//1.創建空白圖片
BufferedImageimage=newBufferedImage(
WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
//2.獲取圖片畫筆
Graphicsgraphic=image.getGraphics();
//3.設置畫筆顏色
graphic.setColor(Color.LIGHT_GRAY);
//4.繪制矩形背景
graphic.fillRect(0,0,WIDTH,HEIGHT);
//5.畫隨機字元
Randomran=newRandom();
for(inti=0;i<SIZE;i++){
//取隨機字元索引
intn=ran.nextInt(chars.length);
//設置隨機顏色
graphic.setColor(getRandomColor());
//設置字體大小
graphic.setFont(newFont(
null,Font.BOLD+Font.ITALIC,FONT_SIZE));
//畫字元
graphic.drawString(
chars[n]+"",i*WIDTH/SIZE,HEIGHT/2);
//記錄字元
sb.append(chars[n]);
}
//6.畫干擾線
for(inti=0;i<LINES;i++){
//設置隨機顏色
graphic.setColor(getRandomColor());
//隨機畫線
graphic.drawLine(ran.nextInt(WIDTH),ran.nextInt(HEIGHT),
ran.nextInt(WIDTH),ran.nextInt(HEIGHT));
}
//7.返回驗證碼和圖片
returnnewObject[]{sb.toString(),image};
}

/**
*隨機取色
*/
(){
Randomran=newRandom();
Colorcolor=newColor(ran.nextInt(256),
ran.nextInt(256),ran.nextInt(256));
returncolor;
}

publicstaticvoidmain(String[]args)throwsIOException{
Object[]objs=createImage();
BufferedImageimage=(BufferedImage)objs[1];
OutputStreamos=newFileOutputStream("d:/1.png");
ImageIO.write(image,"jpeg",os);
os.close();
}

}