|
@@ -0,0 +1,67 @@
|
|
|
+package com.management.platform.util;
|
|
|
+
|
|
|
+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.QRCodeWriter;
|
|
|
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
|
|
|
+
|
|
|
+import javax.imageio.ImageIO;
|
|
|
+import java.awt.*;
|
|
|
+import java.awt.image.BufferedImage;
|
|
|
+import java.io.File;
|
|
|
+import java.io.IOException;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+public class QRCodeUtil {
|
|
|
+
|
|
|
+ /**字符串生成二维码*/
|
|
|
+ public static void generateQRCodeImage(String text, int width, int height, String filePath)
|
|
|
+ throws WriterException, IOException {
|
|
|
+ QRCodeWriter qrCodeWriter = new QRCodeWriter();
|
|
|
+ Map<EncodeHintType, Object> hints = new HashMap<>();
|
|
|
+ hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
|
|
|
+ hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
|
|
+ hints.put(EncodeHintType.MARGIN, 1);
|
|
|
+
|
|
|
+ BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
|
|
|
+
|
|
|
+ BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
|
|
+ image.createGraphics();
|
|
|
+
|
|
|
+ Graphics2D graphics = (Graphics2D) image.getGraphics();
|
|
|
+ graphics.setColor(Color.WHITE);
|
|
|
+ graphics.fillRect(0, 0, width, height);
|
|
|
+ graphics.setColor(Color.BLACK);
|
|
|
+
|
|
|
+ for (int i = 0; i < width; i++) {
|
|
|
+ for (int j = 0; j < height; j++) {
|
|
|
+ if (bitMatrix.get(i, j)) {
|
|
|
+ graphics.fillRect(i, j, 1, 1);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ ImageIO.write(image, "PNG", new File(filePath));
|
|
|
+ }
|
|
|
+
|
|
|
+ /**根据路径解析二维码图片*/
|
|
|
+ public static String decodeQRCode(String filePath) throws IOException {
|
|
|
+ BufferedImage qrCodeImage = ImageIO.read(new File(filePath));
|
|
|
+ LuminanceSource source = new BufferedImageLuminanceSource(qrCodeImage);
|
|
|
+ BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
|
|
|
+
|
|
|
+ try {
|
|
|
+ Map<DecodeHintType, Object> hints = new HashMap<>();
|
|
|
+ hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
|
|
|
+
|
|
|
+ Result result = new MultiFormatReader().decode(bitmap, hints);
|
|
|
+ return result.getText();
|
|
|
+ } catch (NotFoundException e) {
|
|
|
+ System.out.println("未找到二维码: " + e.getMessage());
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+}
|