前言:本工具選擇了Zxing,他是一個開源的,使用java實現多種格式的1D/2D條碼影像處理庫,
1.pom新增依賴
<!-- 二維碼生成&識別元件 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency>
2.二維碼生成工具類
import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import org.apache.commons.lang3.StringUtils; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; public class QRCodeUtil { /** * 生成二維碼 * * @param content 二維碼對應的URL * @param width 二維碼圖片寬度 * @param height 二維碼圖片高度 * @return */ public String createQRCode(String content, int width, int height) throws IOException { String resultImage = ""; //除了尺寸,傳入內容不能為空 if (!StringUtils.isEmpty(content)) { ServletOutputStream stream = null; ByteArrayOutputStream os = new ByteArrayOutputStream(); //二維碼引數 @SuppressWarnings("rawtypes") HashMap<EncodeHintType, Comparable> hints = new HashMap<>(); //指定字元編碼為“utf-8” hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //L M Q H四個糾錯等級從低到高,指定二維碼的糾錯等級為M //糾錯級別越高,可以修正的錯誤就越多,需要的糾錯碼的數量也變多,相應的二維嗎可儲存的資料就會減少 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); //設定圖片的邊距 hints.put(EncodeHintType.MARGIN, 1); try { //zxing生成二維碼核心類 QRCodeWriter writer = new QRCodeWriter(); //把輸入文字按照指定規則轉成二維嗎 BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints); //生成二維碼圖片流 BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix); //輸出流 ImageIO.write(bufferedImage, "png", os); /** * 原生轉碼前面沒有 data:image/png;base64 這些欄位,返回給前端是無法被解析,所以加上字首 */ resultImage = new String("data:image/png;base64," + EncryptUtil.encodeBase64(os.toByteArray())); return resultImage; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("生成二維碼出錯"); } finally { if (stream != null) { stream.flush(); stream.close(); } } } return null; } }
3.附加解碼工具類內方法
public static String encodeBase64(byte[] bytes){ String encoded = Base64.getEncoder().encodeToString(bytes); return encoded; }
4.呼叫工具類
QRCodeUtil qrCodeUtil = new QRCodeUtil(); System.out.println(qrCodeUtil.createQRCode("http://address:port/url", 200, 200));
5.結果分析:
最後一行黑字複製下來直接貼在瀏覽器,掃碼後即可跳轉到上述具體路徑
6.小tips:前端直接用img標籤接收即可展示效果