相关JAR包:
实例代码:
1 /** 2 * GET方法测试 3 * @author:lll 4 * @throws IOException 5 * @throws FileNotFoundException 6 * @time:2017年7月20日下午1:53:30 7 */ 8 @SuppressWarnings("deprecation") 9 @RequestMapping(value = "/getTest", method = RequestMethod.GET)10 public String getTest(HttpServletRequest request, Model model)11 throws FileNotFoundException, IOException {12 String str = "天王盖地虎.宝塔镇妖河";// 二维码内容13 String path = "E:\\files\\hhs3.png"; // 保存图片位置14 String xo = Thread.currentThread().getContextClassLoader().getResource("/").getPath() + "/img/"15 + "hhs3.png"; // 获取图片路径16 BitMatrix byteMatrix = null;17 String imgPath = "E:\\files\\hhs3.png";18 @SuppressWarnings("unused")19 BufferedImage image = ImageIO.read(new FileInputStream(imgPath));20 try {21 Hashtablehints = new Hashtable ();22 hints.put(EncodeHintType.MARGIN, 1); // 设置二维码空白边框的大小 1-4,1是最小 4 是默认的国标23 24 // 生成二维码25 byteMatrix = new MultiFormatWriter().encode(new String(str.getBytes("UTF-8"), "iso-8859-1"),26 BarcodeFormat.QR_CODE, 200, 200, hints);27 28 File file = new File(path);29 OutputStream stream = new OutputStream() {30 31 @Override32 public void write(int b) throws IOException {33 }34 };35 MatrixToImageWriter.writeToFile(byteMatrix, "png", file);36 MatrixToImageWriter.writeToStream(byteMatrix, "png", stream); // 将对应的二维码写入图片流37 BufferedImage img = MatrixToImageWriter.toBufferedImage(byteMatrix);38 HttpServletResponse resp = response;39 ImageIO.write(img, "jpeg", resp.getOutputStream()); // 输出图片40 @SuppressWarnings("unused")41 String head =42 " Document ";45 46 } catch (Exception e) {47 e.printStackTrace();48 }49 return null;50 }