java web项目生成二维码思想

本文使用google的zxing生成


前期准备

引入jar包

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.1</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.1</version>
</dependency>

编写工具类

/**
 * QrCodeUtil.java
 * com.juyo.visa.common.util
 * Copyright (c) 2017, 
*/

package com.juyo.visa.common.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import lombok.Data;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.uxuexi.core.common.util.RandomUtil;

/**
 * TODO(这里用一句话描述这个类的作用)
 * <p>
 * TODO(这里描述这个类补充说明 – 可选)
 *
 * @author  
 * @Date	 2017年12月9日 	 
 */
@Data
public class QrCodeUtil {

	private String fileContextPath;

	/**
	 * 生成二维码
	 * <p>
	 * TODO(这里描述这个方法详情– 可选)
	 *
	 * @param content 二维码的内容
	 * @param filePath临时文件的路径
	 */
	public void encodeQrCode(String content, String filePath) {
		try {
			//需要创建一个临时文件,为了防止出现并发问题,现把二维码文件名用16为的UUID来命名
			String fileName = RandomUtil.uu16() + ".png";
			int width = 300; //二维码图像宽度  
			int height = 300; // 二维码图像高度  
			String format = "png";// 图像类型  
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵  
			Path path = FileSystems.getDefault().getPath(filePath, fileName);
			//由于生成二维码的方法没有返回值,现将二维码临时路径进行保存
			this.fileContextPath = path.toString();
			MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像  
			//System.out.println("输出成功.");
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	/** 
	 * 解析二维码 
	 */
	public void decodeQrCode(String filePath) {
		BufferedImage image;
		try {
			image = ImageIO.read(new File(filePath));
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
			Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码  
			System.out.println("图片中内容:  ");
			System.out.println("author: " + result.getText());
			System.out.println("图片中格式:  ");
			System.out.println("encode: " + result.getBarcodeFormat());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

在业务方法中调用生成二维码方法

		QrCodeUtil qrCodeUtil = new QrCodeUtil();
		//生成二维码的临时路径
		String filepath = request.getContextPath();
		//生成二维码
		qrCodeUtil.encodeQrCode(content, filepath);
		//获取二维码临时文件的路径
		String fileContextPath = qrCodeUtil.getFileContextPath();
		//获取到二维码文件
		File file = new File(fileContextPath);

临时路径通过request获取项目的根目录(为了防止项目在部署的过程中出现系统兼容性问题)

最后可以将生成的file上传到您想上传到 地方。









  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
以下是Java生成二维码并下载的代码示例: ```java // 导入相关包 import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; @Controller @RequestMapping("/qrcode") public class QRCodeController { @GetMapping("/download") @ResponseBody public void downloadQRCode(@RequestParam("content") String content, HttpServletResponse response) throws IOException, WriterException { // 设置二维码参数 int width = 300; // 二维码宽度 int height = 300; // 二维码高度 String format = "png"; // 二维码图片格式 Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 编码格式 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 容错等级 hints.put(EncodeHintType.MARGIN, 1); // 边距 // 生成二维码 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix); // 将二维码图片写入文件 File file = new File("qrcode.png"); ImageIO.write(image, format, file); // 设置响应头,使浏览器能够下载文件 response.setHeader("Content-Disposition", "attachment;filename=qrcode.png"); response.setContentType("application/octet-stream"); response.setContentLength((int) file.length()); // 将文件写入响应流 FileInputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } in.close(); out.close(); } } ``` 以上代码使用Spring Boot框架,通过调用`/qrcode/download`接口,传入二维码内容`content`,即可生成二维码并下载到本地。其中,二维码参数可以根据需求进行修改。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员老牛了laoliu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值