|
@@ -0,0 +1,69 @@
|
|
|
+package com.zy.bms.utils;
|
|
|
+
|
|
|
+import com.google.zxing.BarcodeFormat;
|
|
|
+import com.google.zxing.MultiFormatWriter;
|
|
|
+import com.google.zxing.common.BitMatrix;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+
|
|
|
+import javax.imageio.ImageIO;
|
|
|
+import java.awt.image.BufferedImage;
|
|
|
+import java.io.File;
|
|
|
+import java.io.IOException;
|
|
|
+
|
|
|
+
|
|
|
+ * 二维码生成工具类
|
|
|
+ *
|
|
|
+ * @author chen_yi
|
|
|
+ * Create on 2021/11/14
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+public class QRCodeUtil {
|
|
|
+ private static final int BLACK = 0xFF000000;
|
|
|
+ private static final int WHITE = 0xFFFFFFFF;
|
|
|
+ private static final int WIDTH = 200;
|
|
|
+ private static final int HEIGHT = 200;
|
|
|
+ private static final String localFilePath = "/chenyi/open_file/bms/qrcode";
|
|
|
+ private static final String urlPrefix = "http://lq.ailishi.org:4032/chenyi/static/bms/qrcode/";
|
|
|
+ private static final String fileSuffix = ".jpg";
|
|
|
+ private static final String imageFormat = "jpg";
|
|
|
+
|
|
|
+
|
|
|
+ * 根据内容,生成指定宽高、指定格式的二维码图片
|
|
|
+ *
|
|
|
+ * @param content 内容
|
|
|
+ * @return 生成的二维码访问路径
|
|
|
+ */
|
|
|
+ public static String generate(String content) {
|
|
|
+ String url = null;
|
|
|
+ try {
|
|
|
+
|
|
|
+ BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT);
|
|
|
+
|
|
|
+ File outputFile = new File(localFilePath + content + fileSuffix);
|
|
|
+ writeToFile(bitMatrix, outputFile);
|
|
|
+
|
|
|
+ url = urlPrefix + content + fileSuffix;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("二维码生成失败", e);
|
|
|
+ }
|
|
|
+ return url;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ * 生成二维码并存储至本地磁盘
|
|
|
+ *
|
|
|
+ * @param matrix 二维码属性对象
|
|
|
+ * @param file 文件路径
|
|
|
+ */
|
|
|
+ private static void writeToFile(BitMatrix matrix, File file) throws IOException {
|
|
|
+
|
|
|
+ BufferedImage image = new BufferedImage(matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_RGB);
|
|
|
+ for (int x = 0; x < matrix.getWidth(); x++) {
|
|
|
+ for (int y = 0; y < matrix.getHeight(); y++) {
|
|
|
+ image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ ImageIO.write(image, QRCodeUtil.imageFormat, file);
|
|
|
+ }
|
|
|
+}
|