Jelajahi Sumber

file-service 的 ImageUtil 添加一个 decodeQRCode 方法

reghao 1 tahun lalu
induk
melakukan
adab4a50b2

+ 18 - 4
file/file-service/src/main/java/cn/reghao/tnb/file/app/util/ImageUtil.java

@@ -1,10 +1,9 @@
 package cn.reghao.tnb.file.app.util;
 
-import com.google.zxing.BarcodeFormat;
-import com.google.zxing.EncodeHintType;
-import com.google.zxing.MultiFormatWriter;
-import com.google.zxing.WriterException;
+import com.google.zxing.*;
+import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
 import com.google.zxing.common.BitMatrix;
+import com.google.zxing.common.HybridBinarizer;
 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 
 import javax.imageio.ImageIO;
@@ -12,8 +11,11 @@ import java.awt.*;
 import java.awt.image.BufferedImage;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
 import java.util.Hashtable;
+import java.util.Map;
 
 /**
  * @author reghao
@@ -38,6 +40,18 @@ public class ImageUtil {
         return byteArrayOutputStream;
     }
 
+    public String decodeQRCode(InputStream in) throws IOException, NotFoundException {
+        BufferedImage bi = ImageIO.read(in);
+        LuminanceSource source = new BufferedImageLuminanceSource(bi);
+        Binarizer binarizer = new HybridBinarizer(source);
+        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
+
+        Map<DecodeHintType, String> hints = new HashMap<>();
+        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
+        Result result = new MultiFormatReader().decode(binaryBitmap, hints);
+        return result.getText();
+    }
+
     public static ByteArrayOutputStream createImage(String text, int width, int height) throws IOException {
         // 得到图片缓冲区
         BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);