Java?Spring?boot實現(xiàn)生成二維碼
一、引入spring boot依賴:
<!--引入生成二維碼的依賴-->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
二、工具類代碼:
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
/**
* 二維碼生成工具類
*/
public class QrCodeUtils {
private static final String CHARSET = "utf-8";
public static final String FORMAT = "JPG";
// 二維碼尺寸
private static final int QRCODE_SIZE = 300;
// LOGO寬度
private static final int LOGO_WIDTH = 60;
// LOGO高度
private static final int LOGO_HEIGHT = 60;
/**
* 生成二維碼
*
* @param content 二維碼內(nèi)容
* @param logoPath logo地址
* @param needCompress 是否壓縮logo
* @return 圖片
* @throws Exception
*/
public static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (logoPath == null || "".equals(logoPath)) {
return image;
}
// 插入圖片
QrCodeUtils.insertImage(image, logoPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source 二維碼圖片
* @param logoPath LOGO圖片地址
* @param needCompress 是否壓縮
* @throws IOException
*/
private static void insertImage(BufferedImage source, String logoPath,
boolean needCompress) throws Exception {
File file = new File(logoPath);
if (!file.exists()) {
System.err.println(""+logoPath+" 該文件不存在!");
return;
}
Image src = ImageIO.read(new File(logoPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 壓縮LOGO
if (width > LOGO_WIDTH) {
width = LOGO_WIDTH;
}
if (height > LOGO_HEIGHT) {
height = LOGO_HEIGHT;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 繪制縮小后的圖
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 生成二維碼(指定路徑保存)
*
* @param content 內(nèi)容
* @param imgPath logo圖片地址(內(nèi)嵌圖片)
* @param destPath 生成二維碼存放地址
* @param needCompress 是否壓縮logo
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, imgPath, needCompress);
mkdirs(destPath);
// String file = new Random().nextInt(99999999)+".jpg";
// ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
ImageIO.write(image, FORMAT, new File(destPath));
}
/**
* 生成二維碼(直接將二維碼以圖片輸出流返回)
*
* @param content 內(nèi)容
* @param imgPath logo圖片地址(內(nèi)嵌圖片)
* @param needCompress 是否壓縮logo
* @return
* @throws Exception
*/
public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, imgPath, needCompress);
return image;
}
public static void mkdirs(String destPath) {
File file = new File(destPath);
// 當(dāng)文件夾不存在時,mkdirs會自動創(chuàng)建多層目錄,區(qū)別于mkdir.(mkdir如果父目錄不存在則會拋出異常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 生成二維碼(內(nèi)嵌LOGO)
*
* @param content 內(nèi)容
* @param logoPath LOGO地址
* @param output 輸出流
* @param needCompress 是否壓縮LOGO
* @throws Exception
*/
public static void encode(String content, String logoPath, OutputStream output, boolean needCompress)
throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
ImageIO.write(image, FORMAT, output);
}
/**
* 獲取指定文件的輸入流,獲取logo
*
* @param logoPath 文件的路徑
* @return
*/
public static InputStream getResourceAsStream(String logoPath) {
return QrCodeUtils.class.getResourceAsStream(logoPath);
}
/**
* 解析二維碼
*
* @param file
* 二維碼圖片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 解析二維碼
*
* @param path
* 二維碼圖片地址
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
return QrCodeUtils.decode(new File(path));
}
//測試一:
public static void main(String[] args) throws Exception {
String text = "https://blog.csdn.net/weixin_43763430";
String logoPath = "D:\\qrCode\\logo.jpg";
String destPath = "D:\\qrCode\\csdn.jpg";
QrCodeUtils.encode(text,logoPath,destPath,true);
}
}
三、調(diào)用工具類生成二維碼
1、將鏈接生成二維碼圖片并保存到指定路徑
工具類中的主方法是指定了二維碼鏈接的內(nèi)容是博客地址,并保存在D:\qrCode\csdn.jpg,二維碼嵌套了頭像的圖片,期望實現(xiàn)的是生成二維碼后被掃碼直接進(jìn)入到博客也沒。如若不嵌入頭像,直接將logoPath參數(shù)設(shè)為null。
//測試一:
public static void main(String[] args) throws Exception {
String text = "https://blog.csdn.net/weixin_43763430";
String logoPath = "D:\\qrCode\\logo.jpg";
String destPath = "D:\\qrCode\\csdn.jpg";
QrCodeUtils.encode(text,logoPath,destPath,true);
}
運行該主方法后,可在指定路徑中看到生成的二維碼圖片。

2、將鏈接生成二維碼直接顯示在頁面
運用spring boot生成二維碼無需將保存二維碼的圖片,只須前端調(diào)用springboot接口即可在頁面上顯示二維碼。實現(xiàn)了實時生成二維碼。Controller層接口代碼示例如下:
@GetMapping("/anon/coupon/qrCodeTest")
@ApiOperation(value = "獲取二維碼")
public void qrCodeTest(HttpServletResponse response) throws Exception {
String text = "https://blog.csdn.net/weixin_43763430";
String logoPath = "D:\\qrCode\\logo.jpg";
//String destPath = "D:\\qrCode\\csdn.jpg";
QrCodeUtils.encode(text,logoPath,response.getOutputStream(),true);
}
打開瀏覽器訪問該接口地址,頁面就會顯示生成的二維碼。掃描二維碼即可進(jìn)入到博客頁面。

3、將以get請求傳參鏈接生成二維碼
二維碼運用到各種業(yè)務(wù)中,通常需要根據(jù)不同用戶識別其相對應(yīng)的內(nèi)容,如以上示例是訪問的博客主頁面,如若想根據(jù)訪問者傳遞的參數(shù)訪問博客中特定的文章,文章訪問各篇文章是用的get請求方式,即可根據(jù)傳參實現(xiàn)get請求傳入不同參數(shù)生成二維碼的內(nèi)容不同。
@GetMapping("/anon/coupon/qrCodeTest")
@ApiOperation(value = "獲取二維碼")
public void qrCodeTest(@RequestParam(value = "id") String id,HttpServletResponse response) throws Exception {
String text = "https://blog.csdn.net/weixin_43763430/article/details/" + id;
String logoPath = "D:\\qrCode\\logo.jpg";
//String destPath = "D:\\qrCode\\csdn.jpg";
QrCodeUtils.encode(text,logoPath,response.getOutputStream(),true);
}
用瀏覽器訪問該接口地址,頁面生成二維碼,用手機(jī)掃描二維碼即可跳轉(zhuǎn)到博客中該篇文章頁面。

總結(jié)
到此這篇關(guān)于Java Spring boot實現(xiàn)生成二維碼的文章就介紹到這了,更多相關(guān)Java Spring boot生成二維碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot項目執(zhí)行腳本 自動拉取最新代碼并重啟的實例內(nèi)容
在本篇文章里小編給大家整理的是一篇關(guān)于SpringBoot項目執(zhí)行腳本 自動拉取最新代碼并重啟的實例內(nèi)容,有需要的朋友們參考下。2019-12-12
Java中ArrayList與順序表的定義與實現(xiàn)方法
ArrayList是一個實現(xiàn)List接口的類,底層是動態(tài)類型順序表,本質(zhì)也就是數(shù)組,動態(tài)主要體現(xiàn)在它的擴(kuò)容機(jī)制,下面這篇文章主要給大家介紹了關(guān)于Java中ArrayList與順序表的定義與實現(xiàn)的相關(guān)資料,需要的朋友可以參考下2022-07-07
mybatis中如何傳遞單個String類型的參數(shù)
這篇文章主要介紹了mybatis中如何傳遞單個String類型的參數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
SpringBoot+React實現(xiàn)計算個人所得稅
本文將以個人所得稅的計算為例,使用React+SpringBoot+GcExcel來實現(xiàn)這一功能,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以了解下2023-09-09
SpringBoot+Vue+Redis實現(xiàn)單點登錄(一處登錄另一處退出登錄)
小編接到一個需求,需要實現(xiàn)用戶在瀏覽器登錄后,跳轉(zhuǎn)到其他頁面,當(dāng)用戶在其它地方又登錄時,前面用戶登錄的頁面退出登錄,這篇文章主要介紹了SpringBoot+Vue+Redis實現(xiàn)單點登錄,需要的朋友可以參考下2019-12-12

