通过网络资源logo图标生成一个自定义内容的二维码。
引入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.12</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
Java代码
public class HutoolUtil {
/**
* 生成二维码并转换为流
*
* @param qrConfig
* @param content
* @return
*/
public static InputStream createQrCode(QrConfig qrConfig, String content) {
try {
byte[] bytes = QrCodeUtil.generatePng(content, qrConfig);
return new ByteArrayInputStream(bytes);
} catch (QrCodeException e) {
Asserts.customizeException("生成二维码失败!");
}
return null;
}
/**
* 将网络资源图片转成BufferedImage
*
* @param imageUrl
* @return
*/
public static BufferedImage urlToBufferImage(String imageUrl) {
BufferedImage bufferedLogo = null;
try {
bufferedLogo = ImageIO.read(new URL(imageUrl));
} catch (Exception e) {
Asserts.customizeException("生成二维码失败!");
e.printStackTrace();
}
return bufferedLogo;
}
}
//使用
//1、创建QrConfig对象,属性赋值
String logoUrl = "xxxxxx";
QrConfig qrConfig = new QrConfig(300, 300);
qrConfig.setForeColor(Color.BLACK);
qrConfig.setRatio(3);
qrConfig.setImg(HutoolUtil.urlToBufferImage(logoUrl));
String content = "123456";
//2、调用上面的生成二维码并转换为流方法
InputStream inputStream = HutoolUtil.createQrCode(qrConfig, content);
//3、调用第三方图片上传api
String qrCode = TencentCosUtil.commonUpload(inputStream, xxx, xxx, xxx, xxx);
QrConfig源码
QrConfig构造方法中会设置属性的初始值,大家根据使用场景进行设置,如果没有特殊要求,使用默认的即可。
其中,ErrorCorrectionLevel表示的是纠错级别,有四个参数:M,L,H,Q,默认值是M。值由低到高,低级别的像素块更大,可以远距离识别,但是遮挡就会造成无法识别。高级别则相反,像素块小,允许遮挡一定范围,但是像素块更密集。
public class QrConfig {
private static final int BLACK = -16777216;
private static final int WHITE = -1;
protected int width;
protected int height;
protected int foreColor;
protected Integer backColor;
protected Integer margin;
protected ErrorCorrectionLevel errorCorrection;
protected Charset charset;
protected Image img;
protected int ratio;
public static QrConfig create() {
return new QrConfig();
}
public QrConfig() {
this(300, 300);
}
public QrConfig(int width, int height) {
this.foreColor = -16777216;
this.backColor = -1;
this.margin = 2;
this.errorCorrection = ErrorCorrectionLevel.M;
this.charset = CharsetUtil.CHARSET_UTF_8;
this.ratio = 6;
this.width = width;
this.height = height;
}
//...
}