java实现字符串生成二维码图片

前言:记录一下后端生成二维码返回给前端的两种方法

方法1

引入依赖

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

接口实现

@RequestMapping(value = "/exportQuickResponseCode",method = RequestMethod.GET)
	 public Result<?> exportQuickResponseCode(String orderId,String workId,HttpServletRequest request, HttpServletResponse response) throws Exception{
		 String msg = "orderId="+orderId+","+"wokId="+workId;
		 String filename = "Users\\hudad\\Pictures\\Saved Pictures\\1.png";//生成的文件名
		 String path = "c:/" + filename;//生成路径

		 try {
			 File file=new File(path);
			 OutputStream ous=new FileOutputStream(file);
			 Map<EncodeHintType,String> map =new HashMap<EncodeHintType, String>();
			 //设置编码 EncodeHintType类中可以设置MAX_SIZE, ERROR_CORRECTION,CHARACTER_SET,DATA_MATRIX_SHAPE,AZTEC_LAYERS等参数
			 map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
			 map.put(EncodeHintType.MARGIN,"2");
			 //生成二维码
			 BitMatrix bitMatrix = new MultiFormatWriter().encode(msg, BarcodeFormat.QR_CODE,300,300,map);
             //response.getOutputStream();响应给前端
			 MatrixToImageWriter.writeToStream(bitMatrix,"png",response.getOutputStream());
             
		 }catch (Exception e) {
			 e.printStackTrace();
		 }
		 return Result.OK();
	 }

   方法2

引入依赖

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.3.4</version>
</dependency>

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

实现

public Result<?> rqCode(String ordersId, String workOrderId,HttpServletResponse response)  {
   try {
    QrCodeUtil.generate("ordersId=" + ordersId + "," + "workOrderId=" + workOrderId, 300, 300, "png",response.getOutputStream());
   } catch (IOException e) {
    e.printStackTrace();
   }
   System.out.println();
   return Result.OK();
  }

上一篇:idea进行断点快捷键


下一篇:IntelliJ IDEA(十一) :Debug的使用