ZXing 生成、解析二维码图片的小示例
2017-01-17 11:49
501 查看
概述
ZXing是一个开源 Java 类库用于解析多种格式的 1D/2D 条形码。目标是能够对QR编码、Data Matrix、UPC的1D条形码进行解码。 其提供了多种平台下的客户端包括:J2ME、J2SE和Android。
官网:ZXing github仓库
实战
本例演示如何在一个非 android 的 Java 项目中使用 ZXing 来生成、解析二维码图片。安装
maven项目只需引入依赖:<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>
如果非maven项目,就去官网下载发布版本:下载地址
生成二维码图片
ZXing 生成二维码图片有以下步骤:com.google.zxing.MultiFormatWriter根据内容以及图像编码参数生成图像2D矩阵。
com.google.zxing.client.j2se.MatrixToImageWriter根据图像矩阵生成图片文件或图片缓存
BufferedImage。
public void encode(String content, String filepath) throws WriterException, IOException { int width = 100; int height = 100; Map<EncodeHintType, Object> encodeHints = new HashMap<EncodeHintType, Object>(); encodeHints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, encodeHints); Path path = FileSystems.getDefault().getPath(filepath); MatrixToImageWriter.writeToPath(bitMatrix, "png", path); }
解析二维码图片
ZXing 解析二维码图片有以下步骤:使用
javax.imageio.ImageIO读取图片文件,并存为一个
java.awt.image.BufferedImage对象。
将
java.awt.image.BufferedImage转换为 ZXing 能识别的
com.google.zxing.BinaryBitmap对象。
com.google.zxing.MultiFormatReader根据图像解码参数来解析
com.google.zxing.BinaryBitmap。
public String decode(String filepath) throws IOException, NotFoundException { BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath)); LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap bitmap = new BinaryBitmap(binarizer); HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>(); decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); Result result = new MultiFormatReader().decode(bitmap, decodeHints); return result.getText(); }
完整参考示例:测试例代码
以下是一个生成的二维码图片示例:
参考
ZXing github仓库相关文章推荐
- java中ZXing 生成、解析二维码图片的小示例
- Android扫一扫(Zxing),闪光灯,生成二维码图片,解析二维码(条码)等
- Java使用谷歌的zxing生成二维码Qrcode并解析提取二维码图片内容
- 使用zxing生成二维码图片,并解析
- c#裁剪图片后使用zxing生成二维码示例分享
- Android扫一扫(Zxing),闪光灯,生成二维码图片,解析二维码(条码)等
- [置顶] Android扫一扫(Zxing),闪光灯,生成二维码图片,解析二维码(条码)等
- Android平台利用Zxing生成二维码与解析图片中的二维码
- Zxing和QR CODE 生成与解析二维码实例(普通篇)
- 二维码之zxing二维码解析图片资源
- Zxing和QR CODE 生成与解析二维码实例(带logo篇)
- 使用zxing生成嵌图片的二维码【java】
- 二维码图片生成和解析工具类
- zxing生成和解析二维码
- Android及Java使用google.zxing生成和解码(解析)二维码(QRCode)
- ZPL 打印条码、二维码及小票(中文/汉字),生成条码、二维码图片【Asp.Net】-含示例代码
- 使用zxing 生成和解析二维码
- 二维码的生成和解析(包括QRCode.jar和google的zxing.jar)
- servlet中用ZXing生成条码二维码并输出到web页面的示例
- 使用zxing生成嵌图片的二维码【java】