生活中時常會有這種情形,掃碼登陸,掃碼註冊,掃碼訪問某網頁等。其實其中的原理就是,這個二維碼中包含了你要訪問的地址的url,掃碼可以解析其中的url從而進行訪問。
下面以springboot項目來實現,通過掃二維碼訪問我的博客首頁。
引入谷歌二維碼生成器jar包:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
編寫二維碼生成工具類:
public class QRCodeUtil {
public static BitMatrix generateQRCodeStream(String content, HttpServletResponse response) {
//給相應添加頭部信息,主要告訴瀏覽器返回的是圖片流
response.setHeader("Cache-Control", "no-store");
// 不設置緩存
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/png");
//設置圖片的文字編碼以及內邊框
Map<EncodeHintType, Object> hints = new HashMap<>();
//編碼
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//邊框距
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix bitMatrix;
try {
//參數分別爲:編碼內容、編碼類型、圖片寬度、圖片高度,設置參數
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 600, 600, hints);
} catch (WriterException e) {
e.printStackTrace();
return null;
}
return bitMatrix;
}
}
二維碼接口:
@RestController
@RequestMapping("/test")
public class QRCodeTestController {
@GetMapping("/getQrCode")
public void generateQRCode4Product(HttpServletRequest request, HttpServletResponse response) {
String longUrl;
try {
longUrl = "https://blog.csdn.net/chenping1993";
// 生成二維碼
BitMatrix qRcodeImg = QRCodeUtil.generateQRCodeStream(longUrl, response);
// 將二維碼輸出到頁面中
MatrixToImageWriter.writeToStream(qRcodeImg, "png", response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}
啓動項目訪問查看二維碼頁面:
微信或者其他方式掃此二維碼,成功訪問到了我的博客首頁: