ZXing+SpringMvc 生成二維碼圖片渲染到前臺頁面

現實生活中很多地方需要使用二維碼,微信公衆號,支付,下載APP等都可以以二維碼爲入口,掃一掃就可以得到想要的結果。一般來說二維碼都是靜態的,直接通過二維碼生成工具生成二維碼圖片後,直接將靜態圖片嵌入網頁中。而現在的業務需求是APK是不斷更新版本的,你不可能每一次APP版本更新,你就生成一個二維碼,還有你的服務器地址也可能會發生變化,導致這個二維碼不是固定的。對於程序員來說,每次都用工具去生成二維碼實在有點麻煩,肯定會考慮一些一勞永逸的方法。本文就是介紹這個功能的實現。


首先考慮的是使用前臺js框架比如github上stars很高的jQuery-qrcode.js,或者qrcode.js。這也是一個不錯的方法。但是本文前臺使用的是react.js沒有兼容ES6的二維碼生成框架,所以考慮從後臺獲取二維碼圖片。


後臺使用的是java,java生成二維碼的jar包的選擇就多樣些。比如大名鼎鼎的com.google.zxing,本文使用的就是這個工具包。首先在maven下引入這個包

- <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>


既然是下載文件就可以使用SpringMVC的ResponseEntity,泛型爲byte[]。也可以使用原始的HttpServletResponse進行文件的下載,本文使用的是ResponseEntity。


那就可以直接封裝一個下載二維碼圖片的方法。

 /**
     * 生成並下載二維碼
     * @param url 二維碼對於URL
     * @param width 二維碼寬
     * @param height 二維碼高
     * @param format  二維碼格式
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static ResponseEntity<byte[]> getResponseEntity(String url,int width, int height,String format) throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url,
                BarcodeFormat.QR_CODE, width, height, hints);// 生成矩陣
        //將矩陣轉爲Image
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, format, out);//將BufferedImage轉成out輸出流
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(out.toByteArray(),
                headers, HttpStatus.CREATED);
    }
接下來直接調用就可以了,比如:

 @RequestMapping("/downloadIOSAPPQRCode")
    public ResponseEntity<byte[]> downloadIOSAPPController(@RequestParam(required = true)String type)
            throws WriterException, IOException{
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("app.properties");
        Properties props = new Properties();
        props.load(is);
        String appId = (String)props.get(type);
        String url = Constants.APP_STORE_SUFFIX + appId;
        return DownloadUtil.getResponseEntity(url, 150, 150, "png");
    }

前臺直接應用這個接口

<img src={baseURL + '/downloadIOSAPPQRCode?type=teacher'}/>

properties文件放在資源目錄下即可

app.properties文件如下

Patriarch-APP-ID=1213271782
Teacher-APP-ID=1213271782
      
         關注微信公衆號每天學習一點程序員的職業經


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章