配置
maven仓库:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>
- 生成二维码
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 生成二维码
* @author crazy
*
*/
public class CreateQRCode {
public static void main(String[] args) {
int width = 300;//图片的宽度
int height = 300;//图片的高度
String format = "png";//图片的格式
String contents = "www.baidu.com";//图片的内容,即网址链接
//定义二维码的参数
HashMap map = new HashMap();
map.put(EncodeHintType.CHARACTER_SET, "utf-8");//字符集
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//纠错等级LMQH,一般用M
map.put(EncodeHintType.MARGIN, 2);//边距
//生成二维码
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, map);
Path file = new File("D:/img.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.识别二维码
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import javax.imageio.ImageIO;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
/**
* 读取二维码的内容
* @author crazy
*
*/
public class ReadQRCode {
public static void main(String[] args) {
try {
MultiFormatReader formatReader = new MultiFormatReader();
//读取文件识别成一个图片
File file = new File("D:/img.png");
BufferedImage image = ImageIO.read(file);
/*
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
HybridBinarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
*/
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
//定义二维码的参数
HashMap map = new HashMap();
map.put(EncodeHintType.CHARACTER_SET, "utf-8");//字符集
Result result = formatReader.decode(binaryBitmap, map);
System.out.println("解析结果:"+result.toString());
System.out.println("二维码格式:"+result.getBarcodeFormat());
System.out.println("二维码文本内容:"+result.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}