生成base64位圖片驗證碼


import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class CaptchaPic {

    public static void main(String[] args) {
        System.out.println(getCaptchaPic());
    }

    /**
     * 生成base64位圖片驗證碼
     *
     * @return
     * @throws IOException
     */
    public static Map<String, String> getCaptchaPic() {
        int width = 160;
        int height = 60;
        int lines = 10;
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        // 設置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        // 設置字體
        g.setFont(new Font("cmr10", Font.BOLD, (int) (height / 1.2)));
        // 隨機數字
        Random r = new Random(System.currentTimeMillis());
        String code = "";
        for (int i = 0; i < 4; i++) {
            int a = r.nextInt(10);
            Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
            g.setColor(c);
            g.drawString("" + a, 5 + i * width / 4, (int) (height / 1.3) + r.nextInt(height / 8));
            code = code + a;
        }
        // 干擾線
        for (int i = 0; i < lines; i++) {
            Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
            g.setColor(c);
            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }
        g.dispose();// 類似於流中的close()帶動flush()---把數據刷到img對象當中
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Map<String, String> map = new HashMap<>(2);
        try {
            ImageIO.write(img, "jpg", outputStream);
            byte[] base64Img = Base64Utils.encode(outputStream.toByteArray());
            map.put("base64Str", "data:image/jpeg;base64," + new String(base64Img).replaceAll("\n", ""));
            map.put("code", code);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM