项目介绍
ZXing是一个开源的,用Java编写的多格式的1D / 2D条码图像处理库,使用ZXing可以生成、识别QR Code(二维码)、Data Matrix、EAN、UPC、Aztec等。
常用的二维码处理库还有zbar,不过它几年不更新代码了,本文介绍ZXing生成二维码的方法。
生成二维码实现
1)引入依赖
创建maven工程,在pom.xml中引入如下 依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
2)生成二维码方法
package com.pbteach.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.common.util.EncryptUtil;
import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
/**
* <P>
* 工具类
* </p>
*
*/
public class MyUtils {
/**
* 生成二维码
* @param content
* @param width
* @param height
* @return
*/
public String createQRCode(String content, int width, int height) throws IOException {
String resultImage = "";
if (!StringUtils.isEmpty(content)) {
ServletOutputStream stream = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
@SuppressWarnings("rawtypes")
HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定字符编码为“utf-8”
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 指定二维码的纠错等级为中级
hints.put(EncodeHintType.MARGIN, 1); // 设置图片的边距
try {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(bufferedImage, "png", os);
//添加 data:image/png;base64 前缀方便前端解析
resultImage = new String("data:image/png;base64," + EncryptUtil.encodeBase64(os.toByteArray()));
return resultImage;
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(CommonErrorCode.CUSTOM, "二维码生成失败");
} finally {
if (stream != null) {
stream.flush();
stream.close();
}
}
}
return null;
}
}
- 测试
编写在MyUtils类中编写main方法测试 createQRCode
public static void main(String[] args) throws IOException {
MyUtils myUtils = new MyUtils();
System.out.println(myUtils.createQRCode("http://www.pbteach.com/", 200, 200));
}
运行main方法,输出二维码图片的base64编码:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAABRElEQVR42u2YOxLCMAxE5XFBmSNwlBwtPlqOwhEoU3gstJLzAQYqis0MLvDELwWyVmsrop+G/MlXcheMCyatF9XZn6/s5Gp/3pZuY0lqT/OkmOjJLKl6PM3CMoLoTkIsiNKy/Z6M2PbHdA7i2sELEll4URUn6XVqS2l94bmCGck+yke35CO+71UGcxfVxQIpnhN2ImORvAwexIIMtLwIO9Hbph2EZXXaep0yE1P85Nsfivd4trOemIzaD57kWTi4Cy9BgUp2axSIZpYQPjcJT3TRJF/Sg3ZoCYapBeXanfzolqwES4jAJNTdxcIa2EkfUHyYoaa6Z4GVbP3CiNug32Gz8pO1XxA4ucez1ik1iTssupwaNZufuhxqorH9OPnhNecg6/nzngVSsvfBXqBoh/sdlphsdarx6WFqbxXMR/5fsn5LHu2h3xzh77egAAAAAElFTkSuQmCC
将以上编码拷贝到浏览器中,显示二维码图片,实际项目中由前端展示二维码。
用手机扫描以上二维码即可进入指定 Url。
读取二维码
1)编写读取二维码的方法
/**
* 识别二维码
* @param url 二维码图片地址
*/
public void readerQR(String url) throws IOException, NotFoundException {
MultiFormatReader formatReader = new MultiFormatReader();
//读取指定的二维码文件
BufferedImage bufferedImage =ImageIO.read(new URL(url));
BinaryBitmap binaryBitmap= new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
//定义二维码参数
Map hints= new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
Result result = formatReader.decode(binaryBitmap, hints);
//输出二维码信息
System.out.println("网址:"+result.getText());
bufferedImage.flush();
}
2)测试
编写main方法
public static void main(String[] args) throws IOException, NotFoundException {
MyUtils myUtils = new MyUtils();
//生成二维码
// System.out.println(myUtils.createQRCode("http://www.pbteach.com/", 200, 200));
//识别二维码
myUtils.readerQR("http://www.pbteach.com/images/pb.png");
}
执行main方法,控制台输出
网址:http://www.pbteach.com/
说明成功解析二维码。
在二维码添加Logo
详见源代码。
附件
完整代码:https://download.csdn.net/download/weixin_44062339/12049532