当前位置: 首页 > 后端技术 > Java

Java 生成二维码实战

时间:2023-04-01 23:40:21 Java

Java生成二维码简介ZXing是一个开源的Java类库,用于解析各种格式的一维/二维条码。目标是能够解码QR码、数据矩阵、UPC的一维条形码。它提供各种平台下的客户端,包括:J2ME、J2SE和Android。官网:ZXinggithub仓库实战本例演示如何在非androidJava项目中使用ZXing生成和解析二维码图片。安装maven项目只需要引入依赖:com.google.zxingcore3.3.0com.google.zxingjavase3.3.0如果不是maven项目,去官网下载发布版:下载地址生成二维码图片ZXing生成二维码图片的步骤如下:1.com.google.zxing.MultiFormatWriter根据内容和图片编码参数生成图片二维矩阵。2.com.google.zxing.client.j2se.MatrixToImageWriter根据图像矩阵生成图像文件或图像缓存BufferedImage。publicvoidencode(Stringcontent,Stringfilepath)throwsWriterException,IOException{intwidth=100;int高度=100;MapencodeHints=newHashMap();encodeHints.put(EncodeHintType.CHARACTER_SET,"UTF-8");BitMatrixbitMatrix=newMultiFormatWriter().encode(content,BarcodeFormat.QR_CODE,width,height,encodeHints);路径path=FileSystems.getDefault().getPath(filepath);MatrixToImageWriter.writeToPath(bitMatrix,"png",path);}解析二维码图片ZXing解析二维码图片有如下步骤:1.使用javax.imageio.ImageIO读取图片文件,保存为java.awt.image.BufferedImage对象。2.将java.awt.image.BufferedImage转换成ZXing可以识别的com.google.zxing.BinaryBitmap对象。3.com.google.zxing.MultiFormatReader根据图片解码参数解析com.google.zxing.BinaryBitmap。publicStringdecode(Stringfilepath)抛出IOException,NotFoundException{BufferedImagebufferedImage=ImageIO.read(newFileInputStream(filepath));LuminanceSourcesource=newBufferedImageLuminanceSource(bufferedImage);二值化器binarizer=newHybridBinarizer(source);BinaryBitmap位图=newBinaryBitmap(binarizer);HashMapdecodeHints=newHashMap();decodeHints.put(DecodeHintType.CHARACTER_SET,"UTF-8");结果result=newMultiFormatReader().decode(bitmap,decodeHints);返回结果.getText();}