如今用二維碼傳遞消息是如此的流行和快捷,二維碼中 可存儲的信息量比較大,容易識別,內容豐富,能夠儲存文本,連接,名片等等。而且如今支付寶微信等的支付都直接能夠用掃描二維碼進行支付,利用特定的掃碼軟件,可以解析二維碼中的內容。在個人項目中,用到了須要存儲一個二維碼的連接,讓用戶直接掃碼之後就能夠下單的需求。通過查詢,能夠用Google的qrcodegencore.jar的類庫直接生成二維碼。附件中是實現生成二維碼的jar包
接下來用兩個步驟來實現此功能需求前端
一、生成二維碼java
import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import org.apache.commons.lang3.StringUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Hashtable; public class QRGenUtils { private static final int black = 0xFF000000; private static final int = 0xFFFFFFFF; public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.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, matrix.get(x, y) ? black : white); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); ImageIO.write(image, format, file); } public static void createQRImage(String content, int width, int height, String path, String fileName) throws Exception { MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Hashtable hints = new Hashtable(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints); if (StringUtils.isNotBlank(path)) { if (!path.endsWith("/")) { path = path + "/"; } } else { path = ""; } String suffix = "jpg"; if (fileName.indexOf(".") <= -1) { fileName = fileName + "." + suffix; } else { suffix = fileName.split("[.]")[1]; } fileName = path + fileName; File file = new File(fileName); writeToFile(bitMatrix, suffix, file); } public static BufferedImage createQRImageBuffer(String content, int width, int height) throws Exception{ MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Hashtable hints = new Hashtable(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints); BufferedImage image = toBufferedImage(bitMatrix); return image; } }
二、把生成BufferedImage數據流進行Base64編碼apache
BufferedImage qrImageBuffer = QRGenUtils.createQRImageBuffer(content, 200, 200); ByteArrayOutputStream os=new ByteArrayOutputStream(); ImageIO.write(qrImageBuffer, "png", os); Base64 base64 = new Base64(); String base64Img = new String(base64.encode(os.toByteArray()));
而後把編碼後圖片在前端頁面直接取值便可微信
<img id="cashier_page_image" src='data:img/jpg;base64,${base64Img }' style="display: none"/>