spring boot整合谷歌zxing生成二維碼帶圖片
剛寫完點擊驗證碼,又來數字驗證碼,現在再來個二維碼,前陣子被poi全家桶坑了,現在又來碼,不過谷歌還是牛皮,現成的直接拿來用。
引入依賴:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
創建一個工具類:
public class QRCodeUtil {
//編碼格式,採用utf-8
private static final String UNICODE = "utf-8";
//圖片格式
private static final String FORMAT = "JPG";
//二維碼寬度,單位:像素pixels
private static final int QRCODE_WIDTH = 300;
//二維碼高度,單位:像素pixels
private static final int QRCODE_HEIGHT = 300;
//LOGO寬度,單位:像素pixels
private static final int LOGO_WIDTH = 100;
//LOGO高度,單位:像素pixels
private static final int LOGO_HEIGHT = 100;
/**
* 生成二維碼圖片
* @param content 二維碼內容
* @param logoPath 圖片地址
* @param needCompress 是否壓縮
* @return
* @throws Exception
*/
private 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, UNICODE);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT,
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;
}
// 插入圖片
QRCodeUtil.insertImage(image, logoPath, needCompress);
return image;
}
/**
* 插入LOGO
* @param source 二維碼圖片
* @param logoPath LOGO圖片地址
* @param needCompress 是否壓縮
* @throws Exception
*/
private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
File file = new File(logoPath);
if (!file.exists()) {
throw new Exception("logo file not found.");
}
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_WIDTH - width) / 2;
int y = (QRCODE_HEIGHT - 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();
}
/**
* 生成二維碼(內嵌LOGO)
* 調用者指定二維碼文件名
* @param content 二維碼的內容
* @param logoPath 中間圖片地址
* @param destPath 存儲路徑
* @param fileName 文件名稱
* @param needCompress 是否壓縮
* @return
* @throws Exception
*/
public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);
mkdirs(destPath);
//文件名稱通過傳遞
fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length())
+ "." + FORMAT.toLowerCase();
ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
return fileName;
}
/**
* 創建文件夾, mkdirs會自動創建多層目錄,區別於mkdir.(mkdir如果父目錄不存在則會拋出異常)
* @param destPath
*/
public static void mkdirs(String destPath) {
File file = new File(destPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 解析二維碼
* @param path 二維碼圖片路徑
* @return String 二維碼內容
* @throws Exception
*/
public static String decode(String path) throws Exception {
File file = new File(path);
BufferedImage 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, UNICODE);
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
}
新建一個controller,寫一個接口創建:
隨便寫個頁面調用一下接口:
<img id="verification" src="/portal/base/qrcode" style="cursor: pointer;" title="看不清?換一張" />
注意:controller裏面的內容info,可以從前臺傳,也可以自己修改,自己喜歡就好