QRCodeUtils 鏈接轉二維碼

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

 

public class QRCodeUtils {
    /**
     *  生成二維碼
     * */
    public static BitMatrix createCode(String content) throws IOException {
        //二維碼的寬高
        int width = 200;
        int height = 200;

        //其他參數,如字符集編碼
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //容錯級別爲H
        hints.put(EncodeHintType.ERROR_CORRECTION , ErrorCorrectionLevel.H);
        //白邊的寬度,可取0~4
        hints.put(EncodeHintType.MARGIN , 0);

        BitMatrix bitMatrix = null;
        try {
            //生成矩陣,因爲我的業務場景傳來的是編碼之後的URL,所以先解碼
            bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);

            bitMatrix = deleteWhite(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        return bitMatrix;
    }

    /**
     *  刪除生成的二維碼周圍的白邊,根據審美決定是否刪除
     * */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

}

 

/**
 *  生成二維碼
 * */
@RequestMapping(value = "/activityCode")
public void getCode(HttpServletResponse response,HttpServletRequest request) throws IOException {
    String share = (String) request.getSession().getAttribute("share");
    // 設置響應流信息
    response.setContentType("image/jpg");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);

    OutputStream stream = response.getOutputStream();

    //type是1,生成活動詳情、報名的二維碼,type是2,生成活動簽到的二維碼
    //String content = ("");
    String content = ("https://shijietong.keyten.net/login.html?share="+share);
    //獲取一個二維碼圖片
    BitMatrix bitMatrix = QRCodeUtils.createCode(content);
    //以流的形式輸出到前端
    MatrixToImageWriter.writeToStream(bitMatrix , "jpg" , stream);
}

 

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