Java教程

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

本文主要是介绍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();
  }

这篇关于java实现字符串生成二维码图片的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!