maven依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.4</version>
</dependency>
代码
public static String createdQrCodeBase64(String text,int width,int height,String urlstr) throws MalformedURLException {
String base64 = "";
QrConfig qrConfig = new QrConfig(width,height);
//设置边距
qrConfig.setMargin(0);
//设置二维码颜色
qrConfig.setForeColor(Color.BLACK.getRGB());
//设置背景色
qrConfig.setBackColor(Color.WHITE.getRGB());
//二维码中间图片
if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(urlstr)) {
URL url = new URL(urlstr);
Image image = ImgUtil.getImage(url);
qrConfig.setImg(image);
qrConfig.setRatio(5);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
QrCodeUtil.generate(text,qrConfig, ImgUtil.IMAGE_TYPE_PNG,out);
byte[] data = out.toByteArray();
BASE64Encoder base64Encoder = new BASE64Encoder();
base64 = base64Encoder.encode(data);
return "data:image/png;base64,"+base64;
}
方法调用
public static void main(String[] args) throws MalformedURLException {
String s = createdQrCodeBase64("创建二维码测试", 200, 200, null);
System.out.println(s);
}
输出
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAD8UlEQVR42u3dQRLDIAwDQP7/6fQR
bYolLzMcSWnw5qIBzjnnae7fttvPf/v/vz2+oAMCCCCAAAIIIIAAAggggAACCCCAAAIIIIAAUgxk
eru9wLeBTX9/6fUDCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAshuIOlB13RA24ENeP+AAAIIIIAA
AggggAACCCCAAAIIIIAAAggggABSC6Qg6Fq94QoQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEA2
A0k/uM77BwQQQAABBBBALBAggFggQAABBBBAAAEEEEAAAcTBcakF2r5hKiBoBQQQQAABBBBAAAEE
EEAAAQQQQAABBBBAAAGkGEh6f3uBjT/tHRDjAQFEgQMCiAIFBBBAAAEEEEAAAQQQQAABJLg/2ugC
EvRdXn8EAAEEEEAAAQQQQAABBBBA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