项目pom.xml文件中引用jar包
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
<scope>compile</scope>
</dependency>
二维码生成的工具类,使用时直接调用对应的方法即可
import com.alibaba.fastjson.JSONObject;
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 java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class QrCodeUtils {
//第一个参数传json报文则扫二维码展示的就是报文,传入url路径扫二维码调用的就是对应的方法且方法返回界面则扫二维码展示的是界面的内容
//第二三个参数设置二维码的大小,第四个参数是二维码保存的位置
public static String generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
Map<EncodeHintType, Object> hints = new HashMap<>();
// 设置字符编码格式
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 设置二维码边缘与内容的间隙
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
Path path = FileSystems.getDefault().getPath(filePath);
// 输出图片格式,可以是PNG、JPG等 将图片保存到path路径下
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
return path.toString();
}
}
调用
//第一个参数是扫描二维码时候访问的地址用来返回网页的,第二三个参数设置二维码的大小,第四个参数是二维码保存的路径
String path = QrCodeUtils.generateQRCodeImage( filePath1+"zhyj/company/license/qycode/"+applyId, 140,140,filePath + "/docTemp/qr_code/" + fzApproveMedicalProdLicense.getId() + ".jpg");