spring架构生成二维码

spring架构生成二维码

           最近做项目遇到生成二维码的需求,遍历了网上大把的生成方案,觉得太麻烦了,二维码直接生成图片方式,本人觉得太过于浪费服务器内存,使用流的方式我觉得才是上上策.,后来找到很简单的方案,放在这里,供大家参考!

         本人项目是采用maven管理的,故所支持的jar包采用坐标方式加入到仓库,如果你不使用maven管理的话,建议还是将如下2个jar包下载到项目,文章结尾处提供jar包的下载,代码如下:


<!-- 二维码支持包 -->
	        <dependency>
    		   <groupId>com.google.zxing</groupId>
    		   <artifactId>core</artifactId>
    		   <version>3.2.0</version>
		</dependency> 
		
		<dependency>
      		   <groupId>com.google.zxing</groupId>
      		   <artifactId>javase</artifactId>
      		   <version>3.2.0</version>
   	 	</dependency>


此2个jar包缺一不可,jar包下载后即编写生成二维码的代码:

	   /**
	    *  生成web版本二维码
	    * @param url 要生成二维码的路径
	    * @param response response对象
	    * @param width 二维码宽度
	    * @param height 二维码高度
	    * @throws IOException
	    */
	   public void getTwoDimension(String url,HttpServletResponse response,int width,int height) throws IOException{
		   if (url != null && !"".equals(url)) {
	            ServletOutputStream stream = null;
	            try {
	                stream = response.getOutputStream();
	                QRCodeWriter writer = new QRCodeWriter();
	                BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width);
	                MatrixToImageWriter.writeToStream(m, "png", stream);
	            } catch (WriterException e) {
	                e.printStackTrace();
	                logger.error("生成二维码失败!");
	            } finally {
	                if (stream != null) {
	                    stream.flush();
	                    stream.close();
	                }
	            }
	        }
	   }

只要传入response对象和你要生成的路径及高度,宽度就好了,将会使用流的方式将二维码返回.

以下调用二维码的方法:

	/**
	 * 获得二维码
	 * @param request
	 * @param response
	 * @param type
	 */
	@RequestMapping(value = "phoneversion/getTwoDimension",method={RequestMethod.POST,RequestMethod.GET})
	public void getTwoDimensionForIOSs(HttpServletRequest request,HttpServletResponse response){
		 
			 
		MatrixToImageWriters matrixToImageWriters = new MatrixToImageWriters();
		try {
			matrixToImageWriters.getTwoDimension("www.baidu.com", response, 200, 200);
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
	}

在前端页面才用如下方式:

    		<div>
        		<h3 class="theme g-c-base">APP下载</h3>
                        <div class="app-iphone"><img src="<%=path%>/phoneversion/getTwoDimension.do" alt="" ></div>
                </div>

ps:本人项目是采用springMVC架构,这种方式只适合web端,客户端方式请另辟奇径!

下载jar包请点击我

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值