使用java生产二维码

阳光穿透心脏的1/2处 2024-04-08 11:45 114阅读 0赞

maven导入第三方库

  1. <dependency>
  2. <groupId>com.google.zxing</groupId>
  3. <artifactId>core</artifactId>
  4. <version>3.2.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.google.zxing</groupId>
  8. <artifactId>javase</artifactId>
  9. <version>3.2.1</version>
  10. </dependency>

开放API接口

  1. @RequestMapping(value = "qrcode/{w}/{h}", method = RequestMethod.GET)
  2. public void qrcode(@RequestParam("url") String url, @PathVariable(value = "w") Integer width, @PathVariable(value = "h") Integer height, HttpServletRequest request, HttpServletResponse response) {
  3. try {
  4. url = new String(new BASE64Decoder().decodeBuffer(url));
  5. } catch (IOException e) {
  6. LOGGER.error("BASE64进行URL解码失败");
  7. }
  8. String format = "png";
  9. Hashtable hints = new Hashtable();
  10. hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
  11. BitMatrix bitMatrix = null;
  12. File outputFile = new File("tmp.png");
  13. try {
  14. bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
  15. MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
  16. } catch (WriterException | IOException e) {
  17. LOGGER.error("写入失败:"+e.getMessage());
  18. }
  19. FileInputStream fis = null;
  20. response.setContentType("image/png");
  21. try {
  22. OutputStream out = response.getOutputStream();
  23. fis = new FileInputStream(outputFile);
  24. byte[] b = new byte[fis.available()];
  25. fis.read(b);
  26. out.write(b);
  27. out.flush();
  28. } catch (Exception e) {
  29. LOGGER.error("请求失败:" + e.getMessage());
  30. } finally {
  31. if (fis != null) {
  32. try {
  33. fis.close();
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }
  39. }

发表评论

表情:
评论列表 (有 0 条评论,114人围观)

还没有评论,来说两句吧...

相关阅读