引入jar包
com.google.zxing
core
3.0.0
com.google.zxing
javase
3.0.0
二维码工具类
//二维码工具类
public class QrCodeUtil {
public static void generateQRCodeImage(String text, String filePath, int width, int height,boolean deleteWhite) throws WriterException, IOException {
//解决中文乱码
HashMap hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints);
//是否删除白边
if(deleteWhite){
BufferedImage image = deleteWhite(bitMatrix); //去白边的话加这一行
File outputfile = new File(filePath);
ImageIO.write(image, "png", outputfile);
return;
}
//生成文件路径
Path path = FileSystems.getDefault().getPath(filePath);
//输出图像
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
//去白边
public static BufferedImage deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
int width = resMatrix.getWidth();
int height = resMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, resMatrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
}
测试生成二维码
@PostMapping("getQrCode")
public String getQrCode(HttpServletRequest request) throws IOException, WriterException {
String realPath=request.getSession().getServletContext().getRealPath("/uploadFile/");
File directory=new File(realPath);
if (!directory.exists()){
directory.mkdirs();
}
String newPath=realPath+"12345.png";
String text = "二维码信息:";
//输出图像
QrCodeUtil.generateQRCodeImage(text, newPath ,300, 300,true);
return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/uploadFile/12345.png";
}
成功识别



