package com.study.zxing;
import java.io.File;
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.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class ZxingTest {
public static void main(String[] args) {
int width = 600;
int height = 600;
//文件格式
String format = "png";
//二维码内容
String content = "www.baidu.com";
//定义二维码参数
HashMap hints = new HashMap();
//编码显示中文
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//规避错误大小
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//页面大小宽度
hints.put(EncodeHintType.MARGIN, 2);
try {
//生成二维码
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
//生成路径
Path file = new File("F:/JAVA/study_pro/QRCode/QRCode.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
https://share.weiyun.com/5OigXSR (密码:U7wf)
文件如要引入的jar包
二维码解析:
package com.study.zxing;
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.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class DecodeQRCode {
public static void main(String[] args) throws Exception {
//生成解析对象
MultiFormatReader multiFormatReader = new MultiFormatReader();
//要解析的文件路径
File file = new File("F:/JAVA/study_pro/QRCode/QRCode.png");
BufferedImage bufferedImage = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
//定义二维码参数
HashMap hints = new HashMap();
//编码显示中文
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
Result result= multiFormatReader.decode(binaryBitmap,hints);
System.out.println("二维码解析:"+result.toString());
System.out.println("二维码类型:"+result.getBarcodeFormat());
System.out.println("二维码文本:"+result.getText());
}
}