引入Maven
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.9</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
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("發(fā)生錯(cuò)誤, 錯(cuò)誤信息是:{}十饥!", e.getMessage());
}
}
}
Service
@Service
public class QRCodeService {
private final Logger log = LoggerFactory.getLogger(QRCodeService.class);
// 自定義參數(shù)窟勃,這部分是Hutool工具封裝的
private static QrConfig initQrConfig() {
QrConfig config = new QrConfig(300, 300);
// 設(shè)置邊距,既二維碼和背景之間的邊距
config.setMargin(3);
// 設(shè)置前景色绷跑,既二維碼顏色(青色)
config.setForeColor(Color.CYAN);
// 設(shè)置背景色(灰色)
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("發(fā)生錯(cuò)誤! {}砸捏!", 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("發(fā)生錯(cuò)誤谬运! {}!", 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");
}