侧边栏壁纸
博主头像
suringYu

走走停停

  • 累计撰写 35 篇文章
  • 累计创建 11 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

java 生成二维码图片

suringYu
2021-09-30 / 0 评论 / 0 点赞 / 264 阅读 / 1,624 字

比较简单直接上代码

       <!-- 二维码生成依赖 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.0</version>
        </dependency>

    public static void main(String[] args) {
        String base64 = "";
        try {
            BufferedImage image = image(UUID.randomUUID().toString());
            Integer width = image.getWidth();
            Integer height = image.getHeight();
            System.out.println("宽:" + width + " 高:"+height);

            //输出流
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", stream);
            base64 = Base64.encode(stream.toByteArray());
            System.out.println(base64);
            stream.flush();
            stream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    private static BitMatrix encode(String contents) throws WriterException {
        final Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        return new QRCodeWriter().encode(contents, BarcodeFormat.QR_CODE, 320, 320, hints);
    }

    private static BufferedImage image(String contents){
        try {
            return MatrixToImageWriter.toBufferedImage(encode(contents), new MatrixToImageConfig(Color.BLACK.getRGB(), Color.WHITE.getRGB()));
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }	
0

评论区