二维码生成

本文介绍了一种生成带有LOGO的二维码的方法,通过使用zxing库,详细展示了如何设置二维码参数,包括尺寸、留白、格式等,并将LOGO嵌入到二维码中,提供了完整的代码实现。

引入依赖jar包

<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>version=3.3.0</version>
		</dependency>

生成代码

    /**
     * 生成带LOGO二维码文件
     *
     * @param content 二维码内容
     * @param width  宽度
     * @param height 高度
     * @param margin 二维码图片周围的留白
     * @param format 格式,png,jpg等
     * @param fileName 文件名
     * @param filePath 临时存储文件路径
     * @return
     * @throws Exception
     */
    public static File getQRCodeLogoFile(String content, int width, int height, int margin, String format, String fileName,
                                     String filePath,String logoUrl) {
        log.info("getQRCodeFile:{}",fileName);
        Map hints = new HashMap();
        //设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN, margin);
        BitMatrix bitMatrix;
        File originFile = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            // 生成矩阵
            originFile = new File(filePath + File.separator + URLEncoder.encode(fileName,"utf-8"));
            log.info("originFile:{}",filePath + File.separator + URLEncoder.encode(fileName,"utf-8"));
            if (!originFile.exists()) {
                originFile.createNewFile();
            }
            if(StringUtils.isNotBlank(logoUrl)){
                writeToFile(bitMatrix,format,originFile,logoUrl);
            }else{
                Path path = originFile.toPath();
                MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
            }
        } catch (WriterException e) {
            log.warn("生成二维码失败", e);
        } catch (IOException e) {
            log.warn("生成二维码失败", e);
        }
        return originFile;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file,String logoUrl) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        //设置logo图标
        image = LogoConfig.LogoMatrix(image,logoUrl);

        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }else{
            System.out.println("图片生成成功!");
        }
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.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,  (matrix.get(x, y) ? BLACK : WHITE));
            }
        }
        return image;
    }

工具类

public class LogoConfig {
     
    public static BufferedImage LogoMatrix(BufferedImage matrixImage,String logoUrl)
            throws IOException {  
        /** 
         * 读取二维码图片,并构建绘图对象 
         */  
        Graphics2D g2 = matrixImage.createGraphics();  
  
        int matrixWidth = matrixImage.getWidth();  
        int matrixHeigh = matrixImage.getHeight();  
  
        //获取logo,这里可以使用本地文件,也可以由外部传入 
        BufferedImage logo = getRemoteBufferedImage(logoUrl);
        
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        // 开始绘制图片  
        g2.drawImage(logo, 125, 125,  //这里的125,125决定了logo与上下边距,左右边距的距离
                matrixWidth / 6, matrixHeigh / 6, null);// 这里的的/6决定了logo图片的大小
        BasicStroke stroke = new BasicStroke(5, BasicStroke.CAP_ROUND,  
                BasicStroke.JOIN_ROUND);  
        g2.setStroke(stroke);// 设置笔画对象  
        // 指定弧度的圆角矩形  
        RoundRectangle2D.Float round = new RoundRectangle2D.Float(  
                125, 125, matrixWidth / 6,  
                matrixHeigh / 6, 4, 4); ///6这里决定了圆角矩形的大小,4代表矩形边框的宽度
        g2.setColor(Color.white);  
        g2.draw(round);// 绘制圆弧矩形  
  
        g2.dispose();  
        matrixImage.flush();  
        return matrixImage;  
    }
    private static BufferedImage getRemoteBufferedImage(String imageURL) {
        URL url = null;
        InputStream is = null;
        BufferedImage bufferedImage = null;
        try {
            url = new URL(imageURL);
            is = url.openStream();
            bufferedImage = ImageIO.read(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.out.println("imageURL: " + imageURL + ",无效!");
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("imageURL: " + imageURL + ",读取失败!");
            return null;
        } finally {
            try {
                if(is!=null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("imageURL: " + imageURL + ",流关闭异常!");
                return null;
            }
        }
        return bufferedImage;
    }

}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值