java实现生成二维码

1.使用Jar包

  • Zxing-3.1.0.jar
  • javase-3.1.0.jar

2.生成不加Logo的二维码

//1.创建Map集合存放生成二维码的基本配置
Map<EncodeHintType,Object> hints=new HashMap<>();
//设置编码格式
hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
//设置纠错等级L/M/Q/H,纠错等级越高越不易识别,当前设置等级为最高等级为H
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置外边距0 1(2) 3(4 5 6) 7(8 9 10)
hints.put(EncodeHintType.MARGIN,1);

//2.设置生成图片类型
BarcodeFormat format=BarcodeFormat.QR_CODE;
//3.创建位矩阵对象 BitMatrix bitMatrix=new MultiFormatWriter().encode("https://www.baidu.com/",format,100,100,hints); //设置位矩阵转图片的参数前景色,背景色 MatrixToImageConfig config=new MatrixToImageConfig(Color.BLACK.getRGB(), Color.WHITE.getRGB()); //输出到文件中 MatrixToImageWriter.writeToFile(bitMatrix, "png",new File("qrcode.png"),config);

3.创建带logo的二维码

//1.创建Map集合存放生成二维码的基本配置
Map<EncodeHintType,Object> hints=new HashMap<>();
//设置编码格式
hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
//设置纠错等级L/M/Q/H,纠错等级越高越不易识别,当前设置等级为最高等级H
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置外边距0 1(2) 3(4 5 6) 7(8 9 10)
hints.put(EncodeHintType.MARGIN,1);

//2.设置生成图片类型
BarcodeFormat format=BarcodeFormat.QR_CODE;
//3.创建位矩阵对象 BitMatrix bitMatrix=new MultiFormatWriter().encode("https://www.baidu.com/",format,100,100,hints);
//4.生成BufferedImage对象 BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix); //5.加载logo图片 BufferedImage logo= ImageIO.read(new FileInputStream("C:\\Users\\50538\\Downloads\\weixin.png")); //创建BufferedImage对象 BufferedImage code=new BufferedImage(100,100,BufferedImage.TYPE_INT_RGB); //获取画笔 Graphics2D g = code.createGraphics(); //将两张图片绘制到新的BufferedImage对象上 g.drawImage(bufferedImage,0,0,100,100,null); g.drawImage(logo,40,40,20,20,null); //输出带logo的图片到文件 ImageIO.write(code,"png",new File("logo.png"));

3.解析二维码

Map<DecodeHintType,Object> hints=new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET,"utf-8");
BufferedImage image=ImageIO.read(new File("logo.png"));
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
MultiFormatReader reader = new MultiFormatReader();
Result result = reader.decode(binaryBitmap,hints);
posted @ 2022-01-12 00:10  稚终KINO  阅读(379)  评论(0)    收藏  举报