依賴
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.2</version>
</dependency>
生成二維碼
import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class QRCodeUtil {
public static void generate(String content, String path, int width, int height) throws Exception {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, 1); // 邊距
BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToPath(matrix, "PNG", new File(path).toPath());
}
public static void main(String[] args) throws Exception {
generate("https://example.com?id=123", "qrcode.png", 300, 300);
}
}
解析二維碼
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class QRCodeReader {
public static String decode(String imagePath) throws Exception {
BufferedImage image = ImageIO.read(new File(imagePath));
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
public static void main(String[] args) throws Exception {
System.out.println(decode("qrcode.png"));
}
}
核心類說明
| 類 | 用途 |
| MultiFormatWriter | 編碼器,支持多種碼制 |
| BitMatrix | 黑白矩陣模型 |
| MatrixToImageWriter | 將 BitMatrix 輸出為圖片文件/流 |
| BufferedImageLuminanceSource | 將 BufferedImage 轉為亮度源 |
| HybridBinarizer | 自適應二值化,適合掃描圖片 |
| MultiFormatReader | 解碼器,自動識別碼制 |
常見參數調優
EncodeHintType.ERROR_CORRECTION:L/M/Q/H 四級糾錯,默認 L。
EncodeHintType.MARGIN:靜默區邊距,默認 4,掃碼困難可調小。
DecodeHintType.TRY_HARDER:投入更多 CPU 嘗試解碼複雜圖片。