java批量生成二维码并打包成zip浏览器导出

//list:包含了二维码url的list集合
DownloadImage.bashDownload(list, "8",request,response);
public static void bashDownload(List<> urls, String size, HttpServletRequest request, HttpServletResponse response) throws Exception {

        //设置HTTP响应头
        response.reset();//重置 响应头
        // 输入流
        String[] files = new String[urls.size()];
		urls.toArray(files);
        try {
            String downloadFilename = "QrCodes_"+System.currentTimeMillis()+".zip";//文件的名称
            downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码
            response.setContentType("application/x-download");;// 指明response的返回对象是文件流
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            for (int i = 0; i < files.length; i++) {

                BufferedImage bufImg = QrcodeUtil.create(files[i], "png", new Integer(size), "ISO8859-1");
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                BufferedImage tag = new BufferedImage(500, 500,
                        BufferedImage.TYPE_INT_RGB);
                tag.getGraphics().drawImage(bufImg,0,0,500,500,null);
                ImageIO.write(tag, "png", os);
                InputStream inStream = new ByteArrayInputStream(os.toByteArray());

//                URL url = new URL(files[i]);
                zos.putNextEntry(new ZipEntry("qrcode"+ ".png"));
//                InputStream fis = url.openConnection().getInputStream();
                byte[] buffer = new byte[1024];
                int r = 0;
                while ((r = inStream.read(buffer)) != -1) {
                    zos.write(buffer, 0, r);
                }
                inStream.close();
            }
            zos.flush();
            zos.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
public class QrcodeUtil {
	private static Logger log = Logger.getLogger("QrcodeUtil");
public static BufferedImage create(String content, String imgType, int size,String charsetName,char errCorrect,int rectSize,int pixoff) throws Exception{
		BufferedImage bufImg = null;
		try {
			Qrcode qrcodeHandler = new Qrcode();
			// 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
			qrcodeHandler.setQrcodeErrorCorrect(errCorrect);
			qrcodeHandler.setQrcodeEncodeMode('B');
			// 设置设置二维码尺寸,取值范围1-40,值越大尺寸越大,可存储的信息越大
			qrcodeHandler.setQrcodeVersion(size);
			// 获得内容的字节数组,设置编码格式
			byte[] contentBytes = content.getBytes(charsetName);
			// 图片尺寸                   算法(尺寸*4+17)*存储单元宽度+偏移量*2(源代码中算法)
			int imgSize = (17 + 4 * size) * rectSize + pixoff * 2;
			bufImg = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);
			Graphics2D gs = bufImg.createGraphics();
			// 设置背景颜色(白色)
			gs.setBackground(new Color(255,255,255));
			gs.clearRect(0, 0, imgSize, imgSize);
			
			// 设定图像颜色(黑色)
			gs.setColor(Color.BLACK);
			// 输出内容> 二维码
			if (contentBytes.length > 0 && contentBytes.length < 800) {
				boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
				for (int i = 0; i < codeOut.length; i++) {
					for (int j = 0; j < codeOut.length; j++) {
						if (codeOut[j][i]) {
							gs.fillRect(j * rectSize + pixoff, i * rectSize + pixoff, rectSize, rectSize);
						}
					}
				}
			} else {
				throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");
			}
			gs.dispose();
			bufImg.flush();
		} catch (Exception e) {
			log.error("QrcodeUtil create has a exception : " + e.getLocalizedMessage());
			throw e;
		}
		return bufImg;
	}
	}

参考链接:https://blog.csdn.net/a263295782/article/details/89195388

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
批量生成二维码打包,你可以使用以下步骤: 1. 安装 vue-qr 插件:在命令行中运行 `npm install vue-qr --save`,或者在项目目录下运行 `yarn add vue-qr`。 2. 创建一个二维码生成器组件:在 Vue 应用中创建一个新的组件,用于批量生成二维码。在组件中使用 vue-qr 插件来生成二维码。 3. 创建一个数据源:在组件中创建一个数据源,用于存储所有要生成二维码的数据。可以使用数组或对象存储数据。 4. 使用 v-for 指令循环生成二维码:在组件中使用 v-for 指令循环遍历数据源,使用 vue-qr 插件生成二维码,并将生成的二维码添加到页面中。 5. 打包生成的二维码:在组件中添加一个按钮,当用户点击按钮时,使用 jszip 插件将所有二维码打包一个压缩文件,并将文件下载到本地。 以下是一个简单的示例代码: ```html <template> <div> <div v-for="(data, index) in dataSource" :key="index"> <p>{{ data.name }}</p> <qrcode :value="data.code"></qrcode> </div> <button @click="handleDownload">Download</button> </div> </template> <script> import VueQr from 'vue-qr' import JSZip from 'jszip' import FileSaver from 'file-saver' export default { components: { VueQr }, data() { return { dataSource: [ { name: 'Qrcode 1', code: 'https://www.example.com/1' }, { name: 'Qrcode 2', code: 'https://www.example.com/2' }, { name: 'Qrcode 3', code: 'https://www.example.com/3' } ] } }, methods: { handleDownload() { const zip = new JSZip() this.dataSource.forEach((data, index) => { const imgData = this.$refs[`qrcode${index}`][0].$el.toDataURL() zip.file(`${data.name}.png`, imgData.substr(imgData.indexOf(',') + 1), { base64: true }) }) zip.generateAsync({ type: 'blob' }).then((content) => { FileSaver.saveAs(content, 'qrcodes.zip') }) } } } </script> ``` 在上述示例代码中,我们使用了 vue-qr 插件来生成二维码,使用 jszip 插件将所有二维码打包一个压缩文件,并使用 file-saver 插件将文件下载到本地。注意,我们使用了 $refs 来获取每个二维码组件的实例,并将实例转换为图片数据进行打包
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值