1.下载地址:
https://github.com/zxing/zxing/releases
2.开始解压zip做个jar包:
建一个新项目包
(1)core/src/main/java下com文件夹复制到项目src下
(2)javase/src/main/java/com文件夹复制到项目src下
导出做个如图的jar包
3.
(1)建一个新项目
(2)建一个lib文件夹
(3)把jar包拷贝进lib文件夹下导入:
(4)建一个CreateQRCode--controller类.
如下图:
在CreateQRCode.java文件编写代码:
package code;
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 CreateQRCode {
public static void main(String[] args) {
int width=300;
int height=300;
//图片后缀
String format="png";
//携带信息的内容
String content="123456789";
//定义二维码参数:
///CHARACTER_SET---字符集
HashMap hints=new HashMap();
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//常用M
hints.put(EncodeHintType.MARGIN,2);//9数字越大距离周边距离越大
//生成它(内容,宽,高)
try {
BitMatrix bitMatrix=new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);
Path file=new File("/Users/zhang/Desktop/code4.png").toPath();//输出到你的指定路径
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行:
桌面将出现一张二维码图片
解析二维码:
public static void read() throws IOException, NotFoundException {
MultiFormatReader formatReader=new MultiFormatReader();
//指定文件图片路径
File file=new File("/Users/zhang/Desktop/code4.png");
BufferedImage image=ImageIO.read(file);
BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
//参数
//定义二维码参数:
///CHARACTER_SET---字符集
HashMap hints=new HashMap();
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
//得到结果
Result result=formatReader.decode(binaryBitmap,hints);
//解析结果
System.out.println("解析结果=="+result);
System.out.println("二维码格式类型=="+result.getBarcodeFormat());
System.out.println("文本内容=="+result.getText());
}
打印结果:
解析结果==123456789
二维码格式类型==QR_CODE
文本内容==123456789