二維碼:是用某種特定的幾何圖形按一定規律在平面(二維方向上)分布的、黑白相間的、記錄數據符號信息的圖形;在代碼編制上巧妙地利用構成計算機內部邏輯基礎的“0”、“1”比特流的概念,使用若干個與二進制相對應的幾何形體來表示文字數值信息,通過圖象輸入設備或光電掃描設備自動識讀以實現信息自動處理:它具有條碼技術的一些共性:每種碼制有其特定的字符集;每個字符占有一定的寬度;具有一定的校驗功能等。同時還具有對不同行的信息自動識別功能、及處理圖形旋轉變化點。而我在這里要講述的是目前流行的常用二維碼QRCode。
QR Code碼,英文全稱(Quick Response Code)是由Denso公司於1994年9月研制的一種矩陣二維碼符號,它具有一維條碼及其它二維條碼所具有的信息容量大、可靠性高、可表示漢字及圖象多種文字信息、保密防偽性強等優點。——百度百科
QRCode 由於其內部結構的特定布局和設計使得它具有超高速的識讀能力和高糾錯能力。好了詳細的描述大家可以去百度查詢各種資料。在這篇隨筆里我主要采用springboot框架來生成QRCode二維碼。話不多說,直接上碼吧。
步驟一:依賴包
<!-- springboot基礎依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 二維碼生成器依賴 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<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.FileOutputStream;
import java.io.OutputStream;
import java.util.Hashtable;
/**
* @author chaoyou
* @email
* @date 2019-11-22 16:04
* @Description
*/
public class QRCodeUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二維碼尺寸
private static final int QRCODE_SIZE = 300;
// LOGO寬度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;
private static BufferedImage createImage(String content, String imgPath,
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); // 設置二維碼中logo的大小
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 (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入圖片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source 二維碼圖片
* @param imgPath LOGO圖片地址
* @param needCompress 是否壓縮
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println(""+imgPath+" 該文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 壓縮LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = 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();
}
/**
* 生成二維碼(內嵌LOGO)
*
* @param content 內容
* @param imgPath LOGO地址
* @param destPath 存放目錄
* @param needCompress 是否壓縮LOGO
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath,
boolean needCompress,Integer NaireID) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
mkdirs(destPath);
String file = NaireID+".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
}
/**
* 當文件夾不存在時,mkdirs會自動創建多層目錄,區別於mkdir.(mkdir如果父目錄不存在則會拋出異常)
* @param destPath 存放目錄
*/
public static void mkdirs(String destPath) {
File file =new File(destPath);
//當文件夾不存在時,mkdirs會自動創建多層目錄,區別於mkdir.(mkdir如果父目錄不存在則會拋出異常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 生成二維碼(內嵌LOGO)
*
* @param content 內容
* @param imgPath LOGO地址
* @param destPath 存儲地址
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath,Integer NaireID)
throws Exception {
QRCodeUtil.encode(content, imgPath, destPath, false, NaireID);
}
/**
* 生成二維碼
*
* @param content 內容
* @param destPath 存儲地址
* @param needCompress 是否壓縮LOGO
* @throws Exception
*/
public static void encode(String content, String destPath,
boolean needCompress,Integer NaireID) throws Exception {
QRCodeUtil.encode(content, null, destPath, needCompress,NaireID);
}
/**
* 生成二維碼
*
* @param content 內容
* @param destPath 存儲地址
* @param naireid 自定義問卷二維碼編號
* @throws Exception
*/
public static void encode(String content, String destPath,Integer naireid) throws Exception {
QRCodeUtil.encode(content, null, destPath, false,naireid);
}
/**
* 生成二維碼(內嵌LOGO)
*
* @param content 內容
* @param imgPath LOGO地址
* @param output 輸出流
* @param needCompress 是否壓縮LOGO
* @throws Exception
*/
public static void encode(String content, String imgPath,
OutputStream output, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}
/**
* 生成二維碼
*
* @param content 內容
* @param output 輸出流
* @throws Exception
*/
public static void encode(String content, OutputStream output) throws Exception {
QRCodeUtil.encode(content, null, output, false);
}
/**
* 解析二維碼
*
* @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);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
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 QRCodeUtil.decode(new File(path));
}
}
步驟三:生成/解析二維碼方法
package cn.suancloud.pdfjk;
import cn.suancloud.pdfjk.api.util.EncryptUtil;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.qrcode.QRCodeMultiReader;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.encoder.QRCode;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Optional;
/**
* @author chaoyou
* @email lichaoyou@suancioud.cn
* @date 2019-11-21 18:00
* @Description
*/
public class QRCodeGenerator {
private static final String QR_CODE_IMAGE_PATH = "C:\\Users\\Administrator\\Pictures\\myQERCode.jpg";
private static final String CHARSET = "utf-8";
/**
* 生成二維碼
* @param text 二維碼中存放的文本內容
* @param width 長度
* @param height 寬度
* @param filePath 二維碼存放途徑
* @throws Exception
*/
public static void generateQRCodeImage(String text, int width, int height, String filePath) throws Exception {
// 初始化QRC對象
QRCodeWriter qrCodeWriter = new QRCodeWriter();
// 加密文本數據
text = EncryptUtil.encryptAES(text);
// 生成二維碼
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
// 獲取指定路徑的操作權限
Path path = FileSystems.getDefault().getPath(filePath);
// 把生成的二維碼寫入到指定的路徑
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
/**
* 解析二維碼
*
* @param path 二維碼圖片地址
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
// 獲取指定路徑圖片資源的IO
File file = new File(path);
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);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
}
