圖片驗證碼【java版】

圖片驗證碼工具類

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

import javax.imageio.ImageIO;


public class ImageVerificationCode {

    private int weight = 100;           //驗證碼圖片的長和寬
    private int height = 40;
    private String text;                //用來保存驗證碼的文本內容
    private Random r = new Random();    //獲取隨機數對象
    //private String[] fontNames = {"宋體", "華文楷體", "黑體", "微軟雅黑", "楷體_GB2312"};   //字體數組
    //字體數組
    private String[] fontNames = {"Georgia"};
    //驗證碼數組
    private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";

    /**
     * 獲取隨機的顏色
     *
     * @return
     */
    private Color randomColor() {
        int r = this.r.nextInt(225);  //這裏爲什麼是225,因爲當r,g,b都爲255時,即爲白色,爲了好辨認,需要顏色深一點。
        int g = this.r.nextInt(225);
        int b = this.r.nextInt(225);
        return new Color(r, g, b);            //返回一個隨機顏色
    }

    /**
     * 獲取隨機字體
     *
     * @return
     */
    private Font randomFont() {
        int index = r.nextInt(fontNames.length);  //獲取隨機的字體
        String fontName = fontNames[index];
        int style = r.nextInt(4);         //隨機獲取字體的樣式,0是無樣式,1是加粗,2是斜體,3是加粗加斜體
        int size = r.nextInt(10) + 24;    //隨機獲取字體的大小
        return new Font(fontName, style, size);   //返回一個隨機的字體
    }

    /**
     * 獲取隨機字符
     *
     * @return
     */
    private char randomChar() {
        int index = r.nextInt(codes.length());
        return codes.charAt(index);
    }

    /**
     * 畫干擾線,驗證碼干擾線用來防止計算機解析圖片
     *
     * @param image
     */
    private void drawLine(BufferedImage image) {
        int num = r.nextInt(10); //定義干擾線的數量
        Graphics2D g = (Graphics2D) image.getGraphics();
        for (int i = 0; i < num; i++) {
            int x1 = r.nextInt(weight);
            int y1 = r.nextInt(height);
            int x2 = r.nextInt(weight);
            int y2 = r.nextInt(height);
            g.setColor(randomColor());
            g.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 創建圖片的方法
     *
     * @return
     */
    private BufferedImage createImage() {
        //創建圖片緩衝區
        BufferedImage image = new BufferedImage(weight, height, BufferedImage.TYPE_INT_RGB);
        //獲取畫筆
        Graphics2D g = (Graphics2D) image.getGraphics();
        //設置背景色隨機
        g.setColor(new Color(255, 255, r.nextInt(245) + 10));
        g.fillRect(0, 0, weight, height);
        //返回一個圖片
        return image;
    }

    /**
     * 獲取驗證碼圖片的方法
     *
     * @return
     */
    public BufferedImage getImage() {
        BufferedImage image = createImage();
        Graphics2D g = (Graphics2D) image.getGraphics(); //獲取畫筆
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++)             //畫四個字符即可
        {
            String s = randomChar() + "";      //隨機生成字符,因爲只有畫字符串的方法,沒有畫字符的方法,所以需要將字符變成字符串再畫
            sb.append(s);                      //添加到StringBuilder裏面
            float x = i * 1.0F * weight / 4;   //定義字符的x座標
            g.setFont(randomFont());           //設置字體,隨機
            g.setColor(randomColor());         //設置顏色,隨機
            g.drawString(s, x, height - 5);
        }
        this.text = sb.toString();
        drawLine(image);
        return image;
    }

    /**
     * 獲取驗證碼文本的方法
     *
     * @return
     */
    public String getText() {
        return text;
    }

    public static void output(BufferedImage image, OutputStream out) throws IOException                  //將驗證碼圖片寫出的方法
    {
        ImageIO.write(image, "JPEG", out);
    }
}

後端調用實現(Servlet)

import com.ujiuye.utils.ImageVerificationCode;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@WebServlet("/demo4")
public class ImageCode extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ImageVerificationCode ivc = new ImageVerificationCode();
        BufferedImage image = ivc.getImage();
        //獲取驗證碼的文本值
        String text = ivc.getText();
        //將圖片響應給瀏覽器
        ImageIO.write(image, "jpg", resp.getOutputStream());

    }
}

前端頁面實現

<script>
    function chageImgCode() {
      document.getElementById("img").src = "/img?time="+new Date().getTime();
    }
</script>
<html>
  <head>
    <title>index</title>
  </head>
  <body>
  <img id="img" src="/img" onclick="chageImgCode()">
  </body>
</html>

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