java如何批量生成二维码,并返回成压缩包形式?

最近有点忙,现在稍微闲一些,就想写写最近遇到的一些业务。

业务:后台根据前端传入的需生成的数量,生成二维码图片并统一打包成压缩包返回。

效果图:在这里插入图片描述
首先根据一定规则生成二维码字符串,然后返回成list(因为有多条):
在这里插入图片描述

为了线程安全与数据唯一,可以给雪花算法中的nextId加上synchronized static关键字,实现类对象锁。

接着将list里的每个元素转成一个个二维码图片,并打包返回。
在这里插入图片描述
具体实现:

	/**
	 * 获取二维码压缩包
	 * 
	 * @param response
	 * @param list     二维码字符串列表
	 */
	private void getCodeZip(HttpServletResponse response, List<SampleCode> list) {
		// 生成二维码图片
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment; filename=QrCode-" + System.currentTimeMillis() + ".zip");// 压缩包名
		ZipOutputStream zos = null;
		try {
			zos = new ZipOutputStream(response.getOutputStream());
			// zos.setLevel(5);//压缩等级
			for (int j = 0; j < list.size(); j++) {
				String codeString = list.get(j).getCode();// 获取二维码字符串
				BufferedImage qrCode = QrCodeCreateUtil.createQrCode(codeString, 900, "JPEG");// 生成二维码图片
				InputStream inputStream = bufferedImageToInputStream(qrCode);// 将bufferedImage转成inputStream
				zos.putNextEntry(new ZipEntry(j + ".JPEG")); // 压缩文件名称 设置ZipEntry对象
				// zos.setComment("采样二维码"); // 设置注释
				int temp = 0;
				while ((temp = inputStream.read()) != -1) { // 读取内容
					zos.write(temp); // 压缩输出
				}
				inputStream.close(); // 关闭输入流
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != zos) {
					zos.flush();
					zos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 生成包含字符串信息的二维码图片
	 * 
	 * @param content     二维码携带信息
	 * @param qrCodeSize  二维码图片大小
	 * @param imageFormat 二维码的格式
	 * @throws WriterException
	 * @throws IOException
	 */
	public static BufferedImage createQrCode(String content, int qrCodeSize, String imageFormat)
			throws WriterException, IOException {
		// 设置二维码纠错级别MAP
		Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
		hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矫错级别
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		// 创建比特矩阵(位矩阵)的QR码编码的字符串
		BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
		// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
		int matrixWidth = byteMatrix.getWidth();
		int picWidth = matrixWidth - 200;
		int picHeight = matrixWidth - 150;// 除掉二维码过长的底部留白
		BufferedImage image = new BufferedImage(picWidth, picHeight, BufferedImage.TYPE_INT_RGB);
		image.createGraphics();
		Graphics2D graphics = (Graphics2D) image.getGraphics();
		// 画二维码
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, matrixWidth, matrixWidth);
		// 使用比特矩阵画并保存图像
		graphics.setColor(Color.BLACK);
		for (int i = 0; i < matrixWidth; i++) {
			for (int j = 0; j < matrixWidth; j++) {
				if (byteMatrix.get(i, j)) {
					graphics.fillRect(i - 100, j - 100, 1, 1);
				}
			}
		}
		graphics.setColor(Color.BLACK);
		Font font = new Font("黑体", Font.BOLD, 80); // 设置底部文字
		graphics.setFont(font);
		graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // 消除文字锯齿
		// 计算文字长度,计算居中的x点坐标
		FontMetrics fm = graphics.getFontMetrics(font);
		int textWidth = fm.stringWidth(content);
		int widthX = (picWidth - textWidth) / 2;
		graphics.drawString(content, widthX, picHeight);
		graphics.dispose();
		BufferedImage bufferedImage = resize(image, 200, 200);// 设置图片大小,并在底部加上字
		return bufferedImage;
	}
	/**
	 * 设置图片大小,并在底部加上字
	 * 
	 * @param content
	 */
	public static BufferedImage resize(BufferedImage img, int newW, int newH) {
		Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
		BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2d = dimg.createGraphics();
		g2d.drawImage(tmp, 0, 0, null);
		g2d.dispose();
		return dimg;
	}

参考文章:
简单记录一下-二维码生成和解析工具类
浅析Java中synchronized与static synchronized
转:雪花算法的原理和实现Java

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
批量生成二维码并打,你可以使用以下步骤: 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 来获取每个二维码组件的实例,并将实例转换为图片数据进行打

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值