java生成二维码并下载
时间: 2024-01-01 08:21:53 浏览: 38
以下是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`,即可生成二维码并下载到本地。其中,二维码参数可以根据需求进行修改。