說明:筆者重新規劃了博客方向,想更詳細的講解微信小程序的所有技術內容,本文於2020年5月25日初次寫作。
本文首發CSDN,純筆者原創手打,歡迎社會各界朋友來轉載我的文章,希望先來私信我,轉載後文章加上原文地址!
同時筆者也歡迎一起合作共贏,願意寫雜誌,寫書,貢獻自己的一份微薄之力!
本篇主要講解,本文主要介紹:實現微信小程序中自定義二維碼
如果您想系統的學習微信小程序,歡迎關注我的CSDN微信小程序專欄,我將不定期更新所學技術,謝謝!
零:前言
開發微信小程序中,有一個常見的需求,就是“一物一碼”。
比如說,一個租房管理系統,你需要爲每一個房屋,甚至每一個租客,設置一個二維碼,方便覈驗;
比如說,一個餐廳點餐系統,你需要爲每一張桌,甚至每一個座位,設置一個二維碼,方便用戶點餐;
比如說,一個在線社交系統,你需要爲每一個用戶,設置一個二維碼,方便用戶之間添加好友;
在實際開發的系統中,能用到二維碼的項目比比皆是。
那麼,我們如何去生成二維碼,實現客戶的需求呢?
一:二維碼是什麼?
常見的二維碼爲QR Code,QR全稱Quick Response,是一個近幾年來移動設備上超流行的一種編碼方式,它比傳統的Bar Code條形碼能存更多的信息,也能表示更多的數據類型。
二維條碼/二維碼是用某種特定的幾何圖形按一定規律在平面分佈的、黑白相間的、記錄數據符號信息的圖形;在代碼編制上巧妙地利用構成計算機內部邏輯基礎的“0”、“1”比特流的概念,使用若干個與二進制相對應的幾何形體來表示文字數值信息,通過圖象輸入設備或光電掃描設備自動識讀以實現信息自動處理:它具有條碼技術的一些共性:每種碼制有其特定的字符集;每個字符佔有一定的寬度;具有一定的校驗功能等。同時還具有對不同行的信息自動識別功能、及處理圖形旋轉變化點。
二維碼可以這樣用......
●信息獲取(名片、地圖、WIFI密碼、資料)
●網站跳轉(跳轉到微博、手機網站、網站)
●廣告推送(用戶掃碼,直接瀏覽商家推送的視頻、音頻廣告)
●手機電商(用戶掃碼、手機直接購物下單)
●防僞溯源(用戶掃碼、即可查看生產地;同時後臺可以獲取最終消費地)
●優惠促銷(用戶掃碼,下載電子優惠券,抽獎)
●會員管理(用戶手機上獲取電子會員信息、VIP服務)
●手機支付(掃描商品二維碼,通過銀行或第三方支付提供的手機端通道完成支付)
●賬號登錄(掃描二維碼進行各個網站或軟件的登錄)
個人理解:
1.二維碼就是一個字符串,使用QQ、微信等解碼工具掃描二維碼後,會掃出這個字符串;
2.如果這個字符串是一個網址,則會被解碼工具的自帶瀏覽器直接打開;
3.如果使用微信掃描,且該網址(域名)關聯小程序,則會優先打開關聯的小程序;
二:二維碼如何生成?
2.1 :我們需要用到 core-3.3.0.jar 這樣一個jar包。
2.2 : 我們需要兩個工具類
QRCodeUtil
package ypc.zwz.util;
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
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 hints = new Hashtable();
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 (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入圖片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
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();
}
/*
* 生成二維碼
*/
public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
mkdirs(destPath);
System.out.println("++++++++++++++++++++++++++");
System.out.println(destPath);//user.dir指定了當前的路徑
ImageIO.write(image, FORMAT_NAME, new File(destPath));
}
public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
return image;
}
public static void mkdirs(String destPath) {
File file = new File(destPath);
// 當文件夾不存在時,mkdirs會自動創建多層目錄,區別於mkdir.(mkdir如果父目錄不存在則會拋出異常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
public static void encode(String content, String imgPath, String destPath) throws Exception {
QRCodeUtil.encode(content, imgPath, destPath, false);
}
public static void encode(String content, String destPath) throws Exception {
QRCodeUtil.encode(content, null, destPath, false);
}
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);
}
public static void encode(String content, OutputStream output) throws Exception {
QRCodeUtil.encode(content, null, output, false);
}
/*
* 解析二維碼
*/
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 hints = new Hashtable();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path));
}
}
BufferedImageLuminanceSource.java
package ypc.zwz.util;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import com.google.zxing.LuminanceSource;
public class BufferedImageLuminanceSource extends LuminanceSource {
private final BufferedImage image;
private final int left;
private final int top;
public BufferedImageLuminanceSource(BufferedImage image) {
this(image, 0, 0, image.getWidth(), image.getHeight());
}
public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
super(width, height);
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
if (left + width > sourceWidth || top + height > sourceHeight) {
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
for (int y = top; y < top + height; y++) {
for (int x = left; x < left + width; x++) {
if ((image.getRGB(x, y) & 0xFF000000) == 0) {
image.setRGB(x, y, 0xFFFFFFFF); // = white
}
}
}
this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
this.image.getGraphics().drawImage(image, 0, 0, null);
this.left = left;
this.top = top;
}
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
image.getRaster().getDataElements(left, top + y, width, 1, row);
return row;
}
public byte[] getMatrix() {
int width = getWidth();
int height = getHeight();
int area = width * height;
byte[] matrix = new byte[area];
image.getRaster().getDataElements(left, top, width, height, matrix);
return matrix;
}
public boolean isCropSupported() {
return true;
}
public LuminanceSource crop(int left, int top, int width, int height) {
return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
}
public boolean isRotateSupported() {
return true;
}
public LuminanceSource rotateCounterClockwise() {
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = rotatedImage.createGraphics();
g.drawImage(image, transform, null);
g.dispose();
int width = getWidth();
return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
}
}
2.3 編寫測試函數
main.java
package ypc.zwz.main;
import ypc.zwz.util.QRCodeUtil;
public class Main {
public static void main(String[] args) {
for(int id = 1; id<=1;id ++) {
saveHouseTwoDimensionalCode("c:",Long.valueOf(Long.parseLong(""+id)));
}
}
public static int saveHouseTwoDimensionalCode(String filePath,Long id){
String text = "https://ypcqmm.net?id=" + id;
// 二維碼中心的內嵌圖片
String imgPath = filePath+"\\zwz\\logo.png";
// 生成的二維碼的路徑及名稱
String destPath = filePath+"\\zwz\\house_"+String.valueOf(id)+".png";
//生成二維碼
try {
QRCodeUtil.encode(text, imgPath, destPath, true);
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
}
網址(二維碼內容)可以根據實際需求進行更改(String 類型的 text 變量)
內嵌圖片的文件名和位置,也可以按需更改(String 類型的 imgPath 變量)
生成二維碼的圖片文件位置,也可以按需更改(Stringl類型的 destPath 變量)
2.4 運行項目,產生二維碼
然後打開指定的目錄,我的是C盤zwz文件夾
三: 如何關聯到微信小程序?
首先,你需要:
1.請確認你的微信小程序,是不是企業、媒體、政府及其他組織類型小程序;
2.請確認你有沒有通過TCP備案的域名?
如果沒有,可以參考我的另外一篇文章:《騰訊雲服務器備案全流程 40天備案的血與淚》
3.請確認該域名的綁定服務器能否可以用?
如果以上三個條件都具備了,那麼可以參考官網文檔進行掃普通鏈接二維碼打開小程序的配置了。
四: 總結
總而言之,本文講解了微信小程序中,如何生成自定義的二維碼,使得用戶使用微信,掃描該二維碼,可以進入指定的微信小程序。