支付链接转码util

发布时间:2023-05-24 09:27:43

/** *  <p> *      生成二维码的工具类 *  </p> * * @author  * @date  * */public class QRCodeUtils {    /**     *  生成二维码     * @param content 二维码的内容     * @return BitMatrix对象     * */    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;    }    /**     *  删除生成的二维码周围的白边,是否根据审美决定删除审美决定     * @param matrix BitMatrix对象     * @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;    }    /**     * 生成转base64的二维码     * @param content     * @return     */    public static String getQrcodetobase6(String content) {        String img_base64 = null;///转换成base64串        try {            ByteArrayOutputStream stream = new ByteArrayOutputStream();            ///获得二维码图片            BitMatrix bitMatrix = QRCodeUtils.createCode(content);            ////以流的形式输出到前端            MatrixToImageWriter.writeToStream(bitMatrix , "jpg" , stream);            byte[] bytes = stream.toByteArray();            BASE64Encoder encoder = new BASE64Encoder();            img_base64 = encoder.encodeBuffer(bytes).trim();            img_base64 = img_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n        } catch (IOException e) {            throw new RuntimeException(e);        }        return img_base64;    }}

引入依赖

<!--转二维码-->        <dependency>            <groupId>com.google.zxing</groupId>            <artifactId>core</artifactId>            <version>3.5.0</version>        </dependency>        <dependency>            <groupId>com.google.zxing</groupId>            <artifactId>javase</artifactId>            <version>3.5.0</version>        </dependency>

上一篇 poj-1042
下一篇 poj-3026

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题