美文网首页
生成二维码以及带logo二维码的工具类

生成二维码以及带logo二维码的工具类

作者: 青休 | 来源:发表于2020-08-28 17:39 被阅读0次
public class QRCodeUtil {    
    /**
     * 生成普通的二维码
     *
     * @param width   二维码的宽
     * @param height  二维码的高
     * @param content 二维码的内容
     * @param path    二维码的存放路径
     */
    public static String createQrCode(int width, int height, String content, String path) {
        //图片格式,如果是png类型,logo图变成黑白
        String format = "jpg";
        // 1、设置二维码的一些参数
        HashMap hints = new HashMap();
        // 1.1设置字符集
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 1.2设置容错等级;因为有了容错,在一定范围内可以把二维码p成你喜欢的样式 纠错等级【L,M,Q,H】
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 1.3设置外边距;(即白色区域)
        hints.put(EncodeHintType.MARGIN, 2);
        // 2、生成二维码
        String qrCodeName = UUID.randomUUID().toString().replace("-", "") + "." + format;
        try {
            // 2.1定义BitMatrix对象
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            // 2.2、设置二维码存放路径,以及二维码的名字
            Path codePath = new File(path + File.separator + qrCodeName).toPath();
            // 2.3、执行生成二维码
            MatrixToImageWriter.writeToPath(bitMatrix, format, codePath);
        } catch (Exception e) {
            log.error("createQrCode is error e={}", e);
        }
        return qrCodeName;
    }

    /**
     * 生成中间有logo的二维码
     *
     * @param width        二维码的宽
     * @param height       二维码的长
     * @param content      二维码的内容
     * @param logoUrl      logoUrl
     * @param logoCodePath 带logo二维码的路径
     */
    public static String createLogoQrCode(int width, int height, String content, String logoUrl, String logoCodePath) {
        //图片格式,如果是png类型,logo图变成黑白
        String format = "jpg";
        // 1、设置二维码的一些参数
        HashMap hints = new HashMap();
        // 1.1设置字符集
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 1.2设置容错等级;因为有了容错,在一定范围内可以把二维码p成你喜欢的样式
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 1.3设置外边距;(即白色区域)
        hints.put(EncodeHintType.MARGIN, 2);

        // 2、生成二维码
        String qrCodeName = UUID.randomUUID().toString().replace("-", "") + "." + format;
        try {
            // 2.1定义BitMatrix对象
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            // 2.2、设置二维码存放路径,以及二维码的名字
            // 二维码图片的文件
            File qrFile = new File(logoCodePath + File.separator + qrCodeName);
            // logo图片的文件
            File logoFile = new File(logoUrl);
            // 2.3、执行生成二维码
            MatrixToImageWriter.writeToPath(bitMatrix, format, qrFile.toPath());
            // 2.4在二维码中添加logo
            addLogo(qrFile, logoFile, format);

        } catch (Exception e) {
            log.error("createLogoQrCode is error e={}", e);
        }
        return qrCodeName;
    }


    /**
     * @param qrPic   二维码文件路径
     * @param logoPic logo文件路径
     * @param format  图片格式
     */
    private static void addLogo(File qrPic, File logoPic, String format) throws FileNotFoundException {
        if (!qrPic.isFile() || !logoPic.isFile()) {
            throw new FileNotFoundException();
        }

        try {
            // 1、读取二维码图片,并构建绘图对象
            BufferedImage image = ImageIO.read(qrPic);
            //获取画笔
            Graphics2D graph = image.createGraphics();
            // 2、读取logo图片
            BufferedImage logo = ImageIO.read(logoPic);
            //设置二维码大小,太大了会覆盖二维码,此处占1/4
            int widthLogo = logo.getWidth() > image.getWidth() / 4 ? image.getWidth() / 4 : logo.getWidth();
            int heightLogo = logo.getHeight() > image.getHeight() / 4 ? image.getHeight() / 4 : logo.getHeight();
            // 3、计算图片放置的位置
            int x = (image.getWidth() - widthLogo) / 2;
            int y = (image.getHeight() - heightLogo) / 2;
            // 4、绘制图片
            //开始合并并绘制图片
            graph.drawImage(logo, x, y, widthLogo, heightLogo, null);
            graph.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
            //logo边框大小
            graph.setStroke(new BasicStroke(3));
            //logo边框颜色
            graph.setColor(Color.WHITE);
            graph.drawRect(x, y, widthLogo, heightLogo);
            graph.dispose();
            logo.flush();
            image.flush();
            ImageIO.write(image, format, qrPic);

        } catch (Exception e) {
            log.error("addLogo is error e={}", e);

        }
    }

    /**
     * 解析二维码
     *
     * @param codePath 二维码存放全路径
     */
    public static void readQrCode(String codePath) {

        try {

            MultiFormatReader formatReader = new MultiFormatReader();
            File QrCode = new File(codePath);
            BufferedImage image = ImageIO.read(QrCode);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            // 设置二维码的参数
            HashMap hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            Result result = formatReader.decode(binaryBitmap, hints);
            // 打印解析结果
            System.out.println("解析结果--->" + result.toString());
            // 打印二维码格式
            System.out.println("二维码格式--->" + result.getBarcodeFormat());
            // 二维码文本内容
            System.out.println("二维码文本内容--->" + result.getText());
        } catch (Exception e) {
            log.error("readQrCode is error e={}", e);
        }
    }
}

相关文章

网友评论

      本文标题:生成二维码以及带logo二维码的工具类

      本文链接:https://www.haomeiwen.com/subject/efalsktx.html