引入Maven
cn.hutool
hutool-all
5.5.9
com.google.zxing
core
3.3.3
Controller
public class QRCodeController {
@Autowired
private QRCodeService qrCodeService;
@GetMapping("qrCode")
public void getQRCode(String codeContent, HttpServletResponse response) {
try {
qrCodeService.createQRCode2Stream(codeContent, response);
log.info("成功生成二维码!");
} catch (Exception e) {
log.error("发生错误, 错误信息是:{}!", e.getMessage());
}
}
}
Service
@Service
public class QRCodeService {
private final Logger log = LoggerFactory.getLogger(QRCodeService.class);
// 自定义参数,这部分是Hutool工具封装的
private static QrConfig initQrConfig() {
QrConfig config = new QrConfig(300, 300);
// 设置边距,既二维码和背景之间的边距
config.setMargin(3);
// 设置前景色,既二维码颜色(青色)
config.setForeColor(Color.CYAN);
// 设置背景色(灰色)
config.setBackColor(Color.GRAY);
return config;
}
/**
* 生成到文件
*
* @param content
* @param filepath
*/
public void createQRCode2File(String content, String filepath) {
try {
QrCodeUtil.generate(content, QrConfig.create().setImg("C:\\Users\\as2i\\Pictures\\bigData.jpg"), FileUtil.file(filepath));
log.info("生成二维码成功, 位置在:{}!", filepath);
} catch (QrCodeException e) {
log.error("发生错误! {}!", e.getMessage());
}
}
/**
* 生成到流
*
* @param content
* @param response
*/
public void createQRCode2Stream(String content, HttpServletResponse response) {
try {
QrCodeUtil.generate(content, initQrConfig(), "png", response.getOutputStream());
log.info("生成二维码成功!");
} catch (QrCodeException | IOException e) {
log.error("发生错误! {}!", e.getMessage());
}
}
}
test
@Autowired
private QRCodeService qrCodeService;
/**
* 将图片生成二维码
*/
@Test
public void testQRC() {
qrCodeService.createQRCode2File("https://s5.51cto.com/oss/201904/08/e9660e5da629f4da646a3435e888c0fe.jpg", "G:\\QRCode\\test.jpg");
}