項目介紹
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