1.导入依赖
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
2.编写生成类
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
@SuppressWarnings("all")
public class GetQRCode {
private static final int width = 600;//定义图片宽度
private static final int height = 600;//定义图片高度
private static final String type = "png";//定义图片格式
private static String content = null;//内容
public static void getURCodePicture(String content,String path,Integer grade){
int rgb = 0;
//定义二维码的配置,在这里我使用的是HashMap
Hashtable hints = new Hashtable();
//定义字符集,我们设置为utf-8
hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
//设置容错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置边距,二维码边距空白宽度为0
hints.put(EncodeHintType.MARGIN,2);
//确定内容
switch (grade){
case 1:
content = "可以通行!";
break;
case 2:
content = "建议隔离!";
break;
case 3:
content = "必须隔离!";
break;
}
try{
//生成二维码对象,传入各种属性
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE,width,height,hints);
//画图
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//绘制二维码上面的点,根据类型不同生成三色码
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
switch (grade){
case 1:
rgb = bitMatrix.get(i,j)? Color.GREEN.getRGB():Color.WHITE.getRGB();
break;
case 2:
rgb = bitMatrix.get(i,j)? Color.YELLOW.getRGB():Color.WHITE.getRGB();
break;
case 3:
rgb = bitMatrix.get(i,j)? Color.RED.getRGB():Color.WHITE.getRGB();
break;
}
image.setRGB(i,j,rgb);
}
}
//定义路径
File file = new File(path);
//生成路径并生成文件
ImageIO.write(image,type,file);
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
GetQRCode.getURCodePicture("hello","D:/MyIDEApeoject/manage-demo/src/main/resources/static/image/Qcode.png",3);
}
}