From c0a0c6ff009a755614d9b6788d680ed4aca0333f Mon Sep 17 00:00:00 2001
From: ChenJiaHe <763432473@qq.com>
Date: 星期三, 14 四月 2021 20:08:33 +0800
Subject: [PATCH] 优化

---
 src/main/java/com/hx/util/BarCodeUtil.java |   57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/main/java/com/hx/util/QRCodeUtil.java  |    2 +-
 2 files changed, 58 insertions(+), 1 deletions(-)

diff --git a/src/main/java/com/hx/util/BarCodeUtil.java b/src/main/java/com/hx/util/BarCodeUtil.java
new file mode 100644
index 0000000..a73e54d
--- /dev/null
+++ b/src/main/java/com/hx/util/BarCodeUtil.java
@@ -0,0 +1,57 @@
+package com.hx.util;
+
+import com.google.zxing.BarcodeFormat;
+import com.google.zxing.MultiFormatWriter;
+import com.google.zxing.client.j2se.MatrixToImageWriter;
+import com.google.zxing.common.BitMatrix;
+import sun.misc.BASE64Encoder;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+
+public class BarCodeUtil {
+
+    /**
+     * 缁欏墠绔骇鐢熶竴涓潯褰㈢爜
+     *
+     * @param number 缂栫爜
+     * @param width  瀹藉害
+     * @param height 楂樺害
+     */
+    public static String getCode(String number, Integer width, Integer height) {
+        // 鐢熸垚鏉″舰鐮�
+        BufferedImage image = getBarCode(number, width, height);
+        // 浣跨敤娴佺殑鏂瑰紡
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        try {
+            ImageIO.write(image, "png", out);
+        } catch (Exception e) {
+            // log.error("generate code error! error message:{}", "鍑虹幇闂锛�");
+            e.printStackTrace();
+        }
+        // 灏嗘祦杞垚鏁扮粍
+        byte[] bytes = out.toByteArray();
+        BASE64Encoder encoder = new BASE64Encoder();
+        // 鎶婄敓鎴愮殑缂栫爜杩斿洖鍘�
+        return "data:image/png;base64," + encoder.encodeBuffer(bytes).trim();
+    }
+
+    /**
+     * 浜х敓鏉″舰鐮佺殑鏂规硶
+     *
+     * @param number 缂栫爜
+     * @param width  瀹藉害
+     * @param height 楂樺害
+     */
+    public static BufferedImage getBarCode(String number, Integer width, Integer height) {
+        try {
+            BitMatrix bitMatrix = new MultiFormatWriter().encode(number, BarcodeFormat.CODE_128, width, height);
+            return MatrixToImageWriter.toBufferedImage(bitMatrix);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+}
diff --git a/src/main/java/com/hx/util/QRCodeUtil.java b/src/main/java/com/hx/util/QRCodeUtil.java
index 5ef9d11..25fe7a3 100644
--- a/src/main/java/com/hx/util/QRCodeUtil.java
+++ b/src/main/java/com/hx/util/QRCodeUtil.java
@@ -55,7 +55,7 @@
 			bos = new ByteArrayOutputStream();
 			ImageIO.write(image, "JPEG", bos);
 			byte[] buf = bos.toByteArray();
-			return Base64.getEncoder().encodeToString(buf);
+			return "data:image/png;base64,"+Base64.getEncoder().encodeToString(buf);
 		}catch (Exception e){
 			e.printStackTrace();
 		}finally {

--
Gitblit v1.8.0