栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

通过zxing生成二维码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过zxing生成二维码

引入jar包

 
        
            com.google.zxing
            core
            3.0.0
        
        
            com.google.zxing
            javase
            3.0.0
        

二维码工具类

//二维码工具类
public class QrCodeUtil {

    public static void generateQRCodeImage(String text, String filePath, int width, int height,boolean deleteWhite) throws WriterException, IOException {

        //解决中文乱码
        HashMap hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints);

        //是否删除白边
        if(deleteWhite){
            BufferedImage image = deleteWhite(bitMatrix); //去白边的话加这一行
            File outputfile = new File(filePath);
            ImageIO.write(image, "png", outputfile);
            return;
        }
        //生成文件路径
        Path path = FileSystems.getDefault().getPath(filePath);
        //输出图像
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

    }

    //去白边
    public static BufferedImage  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);
            }
        }

        int width = resMatrix.getWidth();
        int height = resMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, resMatrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
}

测试生成二维码

   @PostMapping("getQrCode")
    public String getQrCode(HttpServletRequest request) throws IOException, WriterException {
        String realPath=request.getSession().getServletContext().getRealPath("/uploadFile/");
        File directory=new File(realPath);
        if (!directory.exists()){
            directory.mkdirs();
        }
        String newPath=realPath+"12345.png";
        String text = "二维码信息:";
        //输出图像
        QrCodeUtil.generateQRCodeImage(text, newPath ,300, 300,true);
        return  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/uploadFile/12345.png";
    }

 成功识别

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/630897.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号