Java生成二维码

java

相关JAR包:https://files.cnblogs.com/files/LiLiliang/zxing.zip

实例代码:

 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 Hashtable<EncodeHintType, Integer> hints = new Hashtable<EncodeHintType, Integer>();

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

32 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 "<!doctype html><html lang=\"en\"> <head><meta charset=\"UTF-8\"><meta name=\"Generator\" content=\"EditPlus®\"><meta name=\"Author\" content=\"\"><meta name=\"Keywords\" content=\"\"><meta name=\"Description\" content=\"\"><title>Document</title></head><body><img src=";

43 @SuppressWarnings("unused")

44 String end = xo + "/></body></html>";

45

46 } catch (Exception e) {

47 e.printStackTrace();

48 }

49 return null;

50 }

以上是 Java生成二维码 的全部内容, 来源链接: utcz.com/z/391759.html

回到顶部