生成萬能二維碼 前後端邏輯 完整流程

鄧蘑菇發表於2020-11-23

匯入pom

<dependency>
   <groupId>com.google.zxing</groupId>
   <artifactId>core</artifactId>
   <version>3.3.0</version>
</dependency>
<dependency>
   <groupId>com.google.zxing</groupId>
   <artifactId>javase</artifactId>
   <version>3.3.0</version>
</dependency>

 

生成二維碼工具類

public class QRCodeUtil {
    public static String toQRCode(String str) {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 300, 300, hints);
            BufferedImage image = toBufferedImage(bitMatrix);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            try {
                ImageIO.write(image, "png", outputStream);
                return Base64.encodeBase64String(outputStream.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (WriterException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    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) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }
}

 

生成二維碼controller

@Slf4j
@RestController
@RequestMapping("/qr_code_generator")
@Api(tags = "生成二維碼")
public class QRCodeGeneratorController {

   @GetMapping("/qrimage")
   @ApiOperation(value = "生成二維碼")
   public R encodeQrCode(String uniscid) {
      return new R<>(QRCodeUtil.toQRCode("http://192.168.1.186:8080/enterpriseCode?"+uniscid),"success",0);
   }

}

 

前端展示二維碼

 

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAIAAAD2HxkiAAAGDUlEQVR42u3aMZbDIBBEQd3/0vIF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