Java生成二維碼圖片,手機軟件掃碼後跳轉網頁

一、創建maven工程,添加如下依賴

 <dependencies>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.0.0</version>
        </dependency>
</dependencies>

二、代碼

/**
 * @Description
 * @Auther: 笑笑
 * @Date: 20:05 2019/9/28
 */
public class QRCode {

    public static void main(String[] args) {
        // 定義要生成二維碼的基本參數
        int width = 300;
        int height = 300;
        String type = "png";
        String content = "http://www.baidu.com"; //要跳轉的網頁

        // 定義二維碼的配置,使用HashMap
        HashMap<EncodeHintType, Object> hints = new HashMap();
        // 字符集,內容使用的編碼
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 容錯等級,H、L、M、Q
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 邊距,二維碼距離邊的空白寬度
        hints.put(EncodeHintType.MARGIN, 2);

        try {
            // 生成二維碼對象,傳入參數:內容、碼的類型、寬高、配置
            BitMatrix bitMatrix =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            // 定義一個路徑對象,生成圖片的路徑
            Path file = new File("C:\\Users\\Administrator\\Desktop\\code.png").toPath();
            // 生成二維碼,傳入二維碼對象、生成圖片的格式、生成的路徑
            MatrixToImageWriter.writeToPath(bitMatrix, type, file);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

運行main函數,就可以看到桌面上會生成一個code.png的二維碼,使用手機瀏覽器或微信等軟件掃碼,即可跳轉至百度首頁!

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