首页 Java java教程 Java利用Zxing生成二维码的简单实例

Java利用Zxing生成二维码的简单实例

Jan 07, 2017 am 10:58 AM

Zxing是Google提供的关于条码(一维码、二维码)的解析工具,提供了二维码的生成与解析的方法,现在我简单介绍一下使用Java利用Zxing生成与解析二维码

1、二维码的生成

1.1 将Zxing-core.jar 包加入到classpath下。

1.2 二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类拷贝到源码中,这里我将该类的源码贴上,可以直接使用。

import com.google.zxing.common.BitMatrix;
  
 import javax.imageio.ImageIO;
 import java.io.File;
 import java.io.OutputStream;
 import java.io.IOException;
 import java.awt.image.BufferedImage;
  
  
 public final class MatrixToImageWriter {
  
  private static final int BLACK = 0xFF000000;
  private static final int WHITE = 0xFFFFFFFF;
  
  private MatrixToImageWriter() {}
  
   
  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 static void writeToFile(BitMatrix matrix, String format, File file)
    throws IOException {
   BufferedImage image = toBufferedImage(matrix);
   if (!ImageIO.write(image, format, file)) {
    throw new IOException("Could not write an image of format " + format + " to " + file);
   }
  }
  
   
  public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
    throws IOException {
   BufferedImage image = toBufferedImage(matrix);
   if (!ImageIO.write(image, format, stream)) {
    throw new IOException("Could not write an image of format " + format);
   }
  }
  
 }
登录后复制

1.3 编写生成二维码的实现代码

try {
        
   String content = "120605181003;http://www.cnblogs.com/jtmjx";
   String path = "C:/Users/Administrator/Desktop/testImage";
    
   MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    
   Map hints = new HashMap();
   hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
   BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400,hints);
   File file1 = new File(path,"餐巾纸.jpg");
   MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
    
 } catch (Exception e) {
   e.printStackTrace();
 }
登录后复制

现在运行后即可生成一张二维码图片,是不是很简单啊? 接下来我们看看如何解析二维码

2、二维码的解析

2.1 将Zxing-core.jar 包加入到classpath下。  

2.2 和生成一样,我们需要一个辅助类( BufferedImageLuminanceSource),同样该类Google也提供了,这里我同样将该类的源码贴出来,可以直接拷贝使用个,省去查找的麻烦

BufferedImageLuminanceSource 
 import com.google.zxing.LuminanceSource;
  
 import java.awt.Graphics2D;
 import java.awt.geom.AffineTransform;
 import java.awt.image.BufferedImage;
  
 public final class BufferedImageLuminanceSource extends LuminanceSource {
  
  private final BufferedImage image;
  private final int left;
  private final int top;
  
  public BufferedImageLuminanceSource(BufferedImage image) {
   this(image, 0, 0, image.getWidth(), image.getHeight());
  }
  
  public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
   super(width, height);
  
   int sourceWidth = image.getWidth();
   int sourceHeight = image.getHeight();
   if (left + width > sourceWidth || top + height > sourceHeight) {
    throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
   }
  
   for (int y = top; y < top + height; y++) {
    for (int x = left; x < left + width; x++) {
     if ((image.getRGB(x, y) & 0xFF000000) == 0) {
      image.setRGB(x, y, 0xFFFFFFFF); // = white
     }
    }
   }
  
   this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
   this.image.getGraphics().drawImage(image, 0, 0, null);
   this.left = left;
   this.top = top;
  }
  
  @Override
  public byte[] getRow(int y, byte[] row) {
   if (y < 0 || y >= getHeight()) {
    throw new IllegalArgumentException("Requested row is outside the image: " + y);
   }
   int width = getWidth();
   if (row == null || row.length < width) {
    row = new byte[width];
   }
   image.getRaster().getDataElements(left, top + y, width, 1, row);
   return row;
  }
  
  @Override
  public byte[] getMatrix() {
   int width = getWidth();
   int height = getHeight();
   int area = width * height;
   byte[] matrix = new byte[area];
   image.getRaster().getDataElements(left, top, width, height, matrix);
   return matrix;
  }
  
  @Override
  public boolean isCropSupported() {
   return true;
  }
  
  @Override
  public LuminanceSource crop(int left, int top, int width, int height) {
   return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
  }
  
  @Override
  public boolean isRotateSupported() {
   return true;
  }
  
  @Override
  public LuminanceSource rotateCounterClockwise() {
  
    int sourceWidth = image.getWidth();
   int sourceHeight = image.getHeight();
  
   AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
  
   BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
  
   Graphics2D g = rotatedImage.createGraphics();
   g.drawImage(image, transform, null);
   g.dispose();
  
   int width = getWidth();
   return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
  }
  
 }
登录后复制

2.3 编写解析二维码的实现代码

try {
             MultiFormatReader formatReader = new MultiFormatReader();
       String filePath = "C:/Users/Administrator/Desktop/testImage/test.jpg";
       File file = new File(filePath);
       BufferedImage image = ImageIO.read(file);;
       LuminanceSource source = new BufferedImageLuminanceSource(image);
       Binarizer binarizer = new HybridBinarizer(source);
       BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
       Map hints = new HashMap();
       hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
       Result result = formatReader.decode(binaryBitmap,hints);
        
             System.out.println("result = "+ result.toString());
       System.out.println("resultFormat = "+ result.getBarcodeFormat());
       System.out.println("resultText = "+ result.getText());
              
     } catch (Exception e) {
       e.printStackTrace();
     }
登录后复制

现在运行后可以看到控制台打印出了二维码的内容。

到此为止,利用Zxing生成和解析二维码就讲述演示完毕,主要为自己做备忘,同时方便有需要的人。

以上这篇Java利用Zxing生成二维码的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持PHP中文网。

更多Java利用Zxing生成二维码的简单实例相关文章请关注PHP中文网!


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

2025年的前4个JavaScript框架:React,Angular,Vue,Svelte 2025年的前4个JavaScript框架:React,Angular,Vue,Svelte Mar 07, 2025 pm 06:09 PM

本文分析了2025年的前四个JavaScript框架(React,Angular,Vue,Susve),比较了它们的性能,可伸缩性和未来前景。 尽管由于强大的社区和生态系统,所有这些都保持占主导地位,但它们的相对人口

如何使用咖啡因或Guava Cache等库在Java应用程序中实现多层缓存? 如何使用咖啡因或Guava Cache等库在Java应用程序中实现多层缓存? Mar 17, 2025 pm 05:44 PM

本文讨论了使用咖啡因和Guava缓存在Java中实施多层缓存以提高应用程序性能。它涵盖设置,集成和绩效优势,以及配置和驱逐政策管理最佳PRA

Spring Boot Snakeyaml 2.0 CVE-2022-1471问题已修复 Spring Boot Snakeyaml 2.0 CVE-2022-1471问题已修复 Mar 07, 2025 pm 05:52 PM

本文介绍了SnakeyAml中的CVE-2022-1471漏洞,这是一个允许远程代码执行的关键缺陷。 它详细介绍了如何升级春季启动应用程序到Snakeyaml 1.33或更高版本的降低风险,强调了依赖性更新

Node.js 20:关键性能提升和新功能 Node.js 20:关键性能提升和新功能 Mar 07, 2025 pm 06:12 PM

Node.js 20通过V8发动机改进可显着提高性能,特别是更快的垃圾收集和I/O。 新功能包括更好的WebSembly支持和精制的调试工具,提高开发人员的生产率和应用速度。

Java的类负载机制如何起作用,包括不同的类载荷及其委托模型? Java的类负载机制如何起作用,包括不同的类载荷及其委托模型? Mar 17, 2025 pm 05:35 PM

Java的类上载涉及使用带有引导,扩展程序和应用程序类负载器的分层系统加载,链接和初始化类。父代授权模型确保首先加载核心类别,从而影响自定义类LOA

冰山:数据湖桌的未来 冰山:数据湖桌的未来 Mar 07, 2025 pm 06:31 PM

冰山是用于大型分析数据集的开放式桌子格式,可提高数据湖的性能和可伸缩性。 它通过内部元数据管理解决了镶木quet/orc的局限

如何在Java中实施功能编程技术? 如何在Java中实施功能编程技术? Mar 11, 2025 pm 05:51 PM

本文使用lambda表达式,流API,方法参考和可选探索将功能编程集成到Java中。 它突出显示了通过简洁性和不变性改善代码可读性和可维护性等好处

如何将Maven或Gradle用于高级Java项目管理,构建自动化和依赖性解决方案? 如何将Maven或Gradle用于高级Java项目管理,构建自动化和依赖性解决方案? Mar 17, 2025 pm 05:46 PM

本文讨论了使用Maven和Gradle进行Java项目管理,构建自动化和依赖性解决方案,以比较其方法和优化策略。

See all articles