使用hutool工具包,主动一个简单方便,pom添加依赖
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.12</version> </dependency>
直接上代码
//设置像素宽高
QrConfig config = new QrConfig(50,50);
//设置边距
config.setMargin(1);
//设置背景色,例如:Color.BLUE,null表示透明背景
config.setBackColor(null);
//生成二维码图片,并转码一下
String codeImg = imageToBase64(QrCodeUtil.generate(code, config));
public static String imageToBase64(BufferedImage bufferedImage) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
try {
ImageIO.write(bufferedImage, "png", baos);//写入流中
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = baos.toByteArray();//转换成字节
BASE64Encoder encoder = new BASE64Encoder();
String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
return png_base64;
}