使用java程序生成二维码以及中文乱码解决问题

因为是maven工程,所以先去idea中配置了maven的选项。
添加了生成二维码所需要的依赖。


            com.google.zxing
            core
            3.3.0
        
        
            com.google.zxing
            javase
            3.3.0
 

核心代码片段

private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        Path path = FileSystems.getDefault().getPath(filePath);

        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

    }

调用此方法并传入二维码相关的参数既能获取二维码。值得注意的是如果内容是中文,需要设置字符编号才能正常显示。

 private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        
        HashMap hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        
        BitMatrix bitMatrix =qrCodeWriter.encode(text,BarcodeFormat.QR_CODE, width, height,hints);
        //BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        Path path = FileSystems.getDefault().getPath(filePath);

        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

    }

这是设置字符编码之后的代码。如下是生成的二维码图片
使用java程序生成二维码以及中文乱码解决问题_第1张图片

你可能感兴趣的:(java基础)