1、添加依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.2</version>
</dependency>
2、数据生成二维码
package com.sample.qrcode;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
public class WriteQRCode {
public static void main(String[] args) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(
"JavaSampleApproach\nJava Technology, Spring Framework",
BarcodeFormat.QR_CODE,
350, 350); // width x height
Path path = FileSystems.getDefault().getPath("JSA-QRCode.png");
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
}
生成二维码如图
3、从二维码读取数据
package com.sample.qrcode;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ReadQRCode {
public static void main(String[] args) throws IOException, NotFoundException {
File QRfile = new File("JSA-QRCode.png");
BufferedImage bufferedImg = ImageIO.read(QRfile);
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImg);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = new MultiFormatReader().decode(bitmap);
System.out.println("Barcode Format: " + result.getBarcodeFormat());
System.out.println("Content: " + result.getText());
}
}
运行结果:
Barcode Format: QR_CODE
Content: Sample
Java Technology, Spring Framework