利用zxing源码包批量生成二维码,压缩并下载到本地
在日常生活中,经常会使用手机扫各种二维码,或进行手机支付,但对于二维码是如何生成的,我做了小小的总结。
此处借用实际项目中业务进行说明:对每个重点部位(实体类:AppKeyPart)生成二维码,并实现批量下载
前端实现(jsp+jquery)
1 <my:access key="keyPart.qrCodeDownload"><input type="button" class="button orange" value="批量下载二维码" id="batchDownloadQrCode" /></my:access>
View Code
1 $(document).ready(function(){ 2 3 //批量下载二维码 4 $("#batchDownloadQrCode").bind("click",function(){ 5 if($("input[name='id']:checked").length <= 0){ 6 $.dialog.alert("请先选择一条或多条数据"); 7 return false; 8 } 9 var ids = ""; 10 $("input[name='id']:checked").each(function(){ 11 ids += $(this).val()+","; 12 }); 13 ids = ids.substring(0, ids.lastIndexOf(",")); 14 window.location.href("${base}/political/keyPart_downloadQrCode.action?ids="+ids); 15 }); 16 17 });
View Code
后端实现(java)
>>>实现类代码
1 public void downloadQrCode(){ 2 String idstr = getRequest().getParameter("ids"); 3 String[] ids = idstr.split(","); 4 5 String userid = SessionManager.getSessionUser().getUserid(); 6 String rootPathText = "/home/tomcat/tempexcel/"; //服务器路径 7 //String rootPathText = "D:\\shy_work\\"; //本机测试路径 8 String realPath = rootPathText + userid + File.separatorChar;//临时文件夹 9 10 for(String id : ids){ 11 KeyPart keyPart = keyPartService.getKeyPart(id); 12 13 AppKeyPart appKeyPart = new AppKeyPart(); 14 appKeyPart.setId(keyPart.getId()); 15 appKeyPart.setBh(keyPart.getBh()); 16 appKeyPart.setMc(keyPart.getMc()); 17 appKeyPart.setSsqy(keyPart.getSsqy()); 18 appKeyPart.setSzjq(keyPart.getSzjq()); 19 appKeyPart.setGdlx(keyPart.getGdlx()); 20 21 JSONObject json = new JSONObject(); 22 json.put("keyPart", appKeyPart); 23 String content = json.toJSONString(); 24 25 //创建文件路径,以userid命名,保证互不影响 26 File file = new File(realPath); 27 if(!file.exists()){ 28 file.mkdir(); 29 } 30 31 String filePath = realPath + keyPart.getId()+ "_" +keyPart.getBh()+".png"; 32 try { 33 QrCodeGenerateUtil.createZxing(filePath, content, 900, "png"); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 } 38 39 try{ 40 File files = new File(realPath); 41 if(!files.exists()){ 42 files.mkdir(); 43 } 44 File[] filelist = files.listFiles(); 45 String zipFileName = userid + ".zip"; 46 47 HttpServletResponse response = this.getResponse(); 48 response.setContentType("application/octet-stream");// 指明response的返回对象是文件流 49 response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);// 设置在下载框默认显示的文件名 50 response.reset(); 51 52 ZipOutputStream zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())); 53 zipos.setMethod(ZipOutputStream.DEFLATED);//设置压缩方法(系统默认是DEFLATED) 54 55 for(File imageFile : filelist){ 56 putZipFiles(imageFile, zipos);//加入压缩文件 57 imageFile.delete();//删除已添加图片 58 } 59 zipos.close();//关闭输出流 60 files.delete(); 61 62 } catch (Exception e) { 63 e.printStackTrace(); 64 } 65 66 }
View Code
1 /** 2 * 将待压缩的文件 加入压缩文件中 3 * @param imageFile 4 * @param zos 5 * @throws IOException 6 * @author Jesse 7 * @date 2018年5月3日上午11:07:34 8 */ 9 public void putZipFiles(File imageFile,ZipOutputStream zos) throws IOException { 10 if(imageFile != null && imageFile.exists()){ 11 //加入压缩文件中 12 zos.putNextEntry(new ZipEntry(imageFile.getName())); 13 14 InputStream is = null; 15 try { 16 is = new FileInputStream(imageFile); 17 byte[] buffer = new byte[1024 * 5]; 18 int len = -1; 19 while((len = is.read(buffer)) != -1) { 20 //把缓冲区的字节写入到ZipEntry 21 zos.write(buffer, 0, len); 22 } 23 zos.closeEntry(); 24 zos.flush(); 25 26 }catch(Exception e) { 27 throw new RuntimeException(e); 28 }finally { 29 if(is != null){ 30 is.close(); 31 } 32 } 33 } 34 }
View Code
>>>工具类代码
1 package cn.gentlesoft.commons.tools; 2 3 import java.awt.image.BufferedImage; 4 import java.io.File; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 import java.util.HashMap; 8 import java.util.Map; 9 10 import javax.imageio.ImageIO; 11 12 import com.alibaba.fastjson.JSONObject; 13 import com.google.zxing.BarcodeFormat; 14 import com.google.zxing.Binarizer; 15 import com.google.zxing.BinaryBitmap; 16 import com.google.zxing.DecodeHintType; 17 import com.google.zxing.EncodeHintType; 18 import com.google.zxing.LuminanceSource; 19 import com.google.zxing.MultiFormatReader; 20 import com.google.zxing.MultiFormatWriter; 21 import com.google.zxing.NotFoundException; 22 import com.google.zxing.Result; 23 import com.google.zxing.client.j2se.BufferedImageLuminanceSource; 24 import com.google.zxing.client.j2se.MatrixToImageWriter; 25 import com.google.zxing.common.BitMatrix; 26 import com.google.zxing.common.HybridBinarizer; 27 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; 28 29 /** 30 * 二维码生成工具 31 * 32 * @author Jesse 33 * 34 */ 35 public class QrCodeGenerateUtil { 36 37 /** 38 * 生成包含字符串信息的二维码图片 39 * 40 * @param os 41 * @param content 42 * @param qrCodeSize 43 * @param imageFormat 44 * @throws Exception 45 */ 46 public static void createZxing(OutputStream os, String content, int qrCodeSize, String imageFormat) 47 throws Exception { 48 // 二维码参数 49 Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); 50 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 51 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 纠错等级L,M,Q,H 52 hints.put(EncodeHintType.MARGIN, 2); // 边距 53 // 创建比特矩阵(位矩阵)的QR码编码的字符串 54 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, 55 hints); 56 MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, os); 57 System.out.println("输出图片成功。。。"); 58 } 59 60 /** 61 * 生成包含字符串信息的二维码图片 62 * 63 * @param path 64 * 二维码图片保存地址 65 * @param content 66 * 二维码携带信息 67 * @param qrCodeSize 68 * 二维码图片大小 69 * @param imageFormat 70 * 二维码图片格式 71 * @throws Exception 72 */ 73 public static void createZxing(String path, String content, int qrCodeSize, String imageFormat) throws Exception { 74 Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); 75 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 76 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 纠错等级L,M,Q,H 77 hints.put(EncodeHintType.MARGIN, 2); // 边距 78 // 创建比特矩阵(位矩阵)的QR码编码的字符串 79 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, 80 hints); 81 File file = new File(path); 82 // 使用比特矩阵画并保存图像 83 MatrixToImageWriter.writeToFile(bitMatrix, imageFormat, file); 84 System.out.println("输出图片成功。。。"); 85 } 86 87 /** 88 * 读取二维码并输出携带的信息 89 * 90 * @param filePath 91 * 二维码图片保存地址 92 */ 93 public static void readZxing(String filePath) { 94 BufferedImage image = null; 95 try { 96 image = ImageIO.read(new File(filePath)); 97 // 将图像转换成二进制位图源 98 LuminanceSource source = new BufferedImageLuminanceSource(image); 99 Binarizer binarizer = new HybridBinarizer(source); 100 BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); 101 Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>(); 102 hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); 103 Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码 104 JSONObject content = JSONObject.parseObject(result.getText()); 105 System.out.println("图片中内容: "); 106 System.out.println("group: " + content.toJSONString()); 107 108 System.out.println("图片中格式: "); 109 System.out.println("encode: " + result.getBarcodeFormat()); 110 } catch (IOException e) { 111 e.printStackTrace(); 112 } catch (NotFoundException e) { 113 e.printStackTrace(); 114 } 115 } 116 117 }
View Code
虽然现在JDK8早已被使用,但由于实际项目使用的是JDK6和IE8浏览器,很多地方受到限制,因此本次使用的二维码第三方源码库,是谷歌的zxing库。core-2.2.java ,javase-2.2.jar
如果是maven项目,也可以在项目pom.xml文件里引入:
1 <dependency> 2 <groupId>com.google.zxing</groupId> 3 <artifactId>core</artifactId> 4 <version>2.2</version> 5 </dependency> 6 7 <dependency> 8 <groupId>com.google.zxing</groupId> 9 <artifactId>javase</artifactId> 10 <version>2.2</version> 11 </dependency>
View Code
到此实现了二维码批量生成 压缩 下载功能!
2018-05-05
转载于:https://www.cnblogs.com/oneBreeze1855/p/8996442.html
利用zxing源码包批量生成二维码,压缩并下载到本地相关推荐
- 利用python生成二维码 以及批量生成二维码
常见的两种简单生成二维码方法,目测均是很好用的 1.MyQR 要求是python3 ,并且二维码上的内容不支持中文 #1.生成普通二维码#在程序中导入MyQR包下的模板myqr,其中word参数接收 ...
- Thinkphp6 生成二维码以及批量生成二维码并保存
1 ,引入 think-qrcode composer require dh2y/think-qrcode 成功后,vendor 文件夹下面会出现 dh2y文件夹 2, 在项目中引用 $code = ...
- 一句代码生成二维码,一句代码生成条形码,批量生成二维码和条形码,步骤教学
生产企业或者物流快递需要用到大量的二维码和条形码,但是要自行编写代码批量生成二维码或者条形码并不容易,涉及的知识面很广. Excel插件<E灵>提供了二维码接口和条形码接口,您只需要一句代 ...
- vue批量生成二维码,打印生成的二维码,并批量下载生成的二维码,qrcode
通过使用 qrcode 生成二维码, 使用 jszip 打包批量二维码文件, 使用 file-saver 下载打包好的zip文件, 使用 vue-print-nb 打印生成的二维码 生成二维码: 打印 ...
- 2023最新在线批量生成二维码网站源码+全开源/UI简约
正文: 在线批量生成二维码网站源码,直接拖服务器就能运行php7.3,程序采用本地接口支持生成接口,生成后自动保存,生成后压缩保存,具体功能可以自己测试,源码无加密. 程序: wwxhes.lanzo ...
- 批量生成二维码系统源码 电脑+手机自适应代码 含安装搭建教程
分享一个批量生成二维码系统源码,一键批量生成包括网址,数字,文字,视频等各种形式的二维码,自动生成压缩包,一键下载.电脑+手机自适应代码,含安装搭建教程. 批量生成二维码系统源码帮助用户快速生成二维码 ...
- springboot+hutool批量生成二维码压缩导出
文章目录 1.引入依赖 2.测试编码 3.批量生成 4.解析excel 5.批量图片压缩 6.上传excel直接将输出流转成压缩包 1.引入依赖 <!-- 生成二维码依赖--><de ...
- 读取excel批量生成二维码
昨天工作需要,让生成二维码,让用草料生成,就需要一个个的复制粘贴,有点麻烦.关键是量特别大,如果传统的复制粘贴要很长时间才可以. 后来想到用程序生成.于是百度了一下生成二维码的方法,别说还很简单,把代 ...
- 利用jquery的qrcode.js插件生成二维码的两种方式的使用
2019独角兽企业重金招聘Python工程师标准>>> 利用jquery的qrcode.js插件生成二维码的额两种方式,canvas(即画布)方式和table方式(原文地址http: ...
最新文章
- Python爬虫高级之JS渗透登录新浪微博 | 知了独家研究
- centos node跟npm 安装
- 2044. 统计按位或能得到最大值的子集数目
- linux内存管理(八)-不连续页分配和页表
- 搭建有效的可复用测试用例,以及后期使用与管理
- ros标准版Action通讯
- 猫眼top前100电影爬取demo(正则初试)
- css3ps—ps直接生成css3 使用方法
- Google Guice
- NPOI word中插入图片
- 1234的平方根用计算机怎么算,平方根计算
- alter user mysql_MySQL使用ALTER USER修改密码
- Springboot+微信小程序自习室管理系统毕业设计源码221535
- Android 白天黑夜模式切换适配及引起的Activity销毁重启解决
- Python中while循环练习——打印星星总结
- 2014广州入户新规则--广州积分入户8月1日起接受申报 详细指引
- 第4次作业类测试代码+105032014070+胡阳洋
- [LeetCode]89.Gray Code
- WinRAR命令行用法
- FDTD快速入门之Lumerical脚本语言Pickup(七)数据获取与分析(Analysis)