【Java開發】生成二維碼

import com.swetake.util.Qrcode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName QRCode
 * @Description TODO 二維碼生成核心類
 * @Author hulin
 * @Date 1/10/2020 8:19 PM
 * @Version 1.0
 */
public class QRCode {
    /**
     * 二維碼生成
     *
     * @param content 二維碼存儲的內容
     * @param imgPath 二維碼存儲的路徑
     */
    public static void getQRCodeImg(String content, String imgPath) {
        /**
         * 二維碼基本信息設置
         */
        //實例化一個Qrcode
        Qrcode qrcode = new Qrcode();
        //設置二維碼的排錯率 L:7%; M:15%;Q:25%;H:30%
        qrcode.setQrcodeErrorCorrect('M');
        //設置編碼 A:英文 N:數字 B:國際編碼 K:中文
        qrcode.setQrcodeEncodeMode('B');
        //設置二維碼的版本
        qrcode.setQrcodeVersion(15);
        /**
         * 開始繪製二維碼
         */
        int width = 235;
        int height = 235;
        //畫板
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //畫筆
        Graphics2D gs = image.createGraphics();
        //設置背景色
        gs.setBackground(Color.WHITE);
        //設置繪製區域
        gs.clearRect(0, 0, width, height);
        //設置畫筆的顏色
        gs.setColor(Color.BLACK);
        //開始繪製,拿到內容
        try {
            byte[] codeOut = content.getBytes(StandardCharsets.UTF_8);
            boolean[][] code = qrcode.calQrcode(codeOut);
            //拿到二維數組裏面的內容
            for (int i = 0; i < code.length; i++) {
                for (int j = 0; j < code.length; j++) {
                    if (code[j][i])
                        gs.fillRect(j * 3 + 2, i * 3 + 2, 3, 3);
                }
            }
            //釋放畫筆
            gs.dispose();
            image.flush();
            //保存
            ImageIO.write(image, "png", new File(imgPath));
            System.out.println("二維碼成功生成!");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        getQRCodeImg("我的第一個二維碼!", "web/img/test.png");
        getQRCodeImg("https://www.baidu.com", "web/img/baidu.png");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章