在公司项目中,经常会遇到一些页面需要弹出一个二维码,然后让用户手机扫描跳转到新页面或者显示内容
本文介绍如何 通过 Java 返回一个二维码图片,当然正常这个活应该让前端做,前端也有相关的轮子
一、引入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
二、Java Demo
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class QRDemo {
private static final String QR_CODE_IMAGE_PATH = "D:/桌面/MyQRCode.png"; // 图片生成到一个目录
private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
public static void main(String[] args) {
try {
// 如果内容是链接,扫码会直接跳转
// generateQRCodeImage("二维码内容", 350, 350, QR_CODE_IMAGE_PATH);
generateQRCodeImage("https://liuyanzhao.com", 350, 350, QR_CODE_IMAGE_PATH);
} catch (WriterException e) {
System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
} catch (IOException e) {
System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
}
}
}
三、SpringBoot(SpringMVC)版本返回图片
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
/**
* 二维码生成
* @author 言曌
* @since 2022/10/9 10:36
*/
@Controller
public class QrCodeController {
@GetMapping("/generateQRCode")
public void generateQRCode(HttpServletResponse response) throws IOException, WriterException {
String content = "https://liuyanzhao.com";
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 350, 350);
OutputStream os = response.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", os);
os.flush();
os.close();
}
}
效果图如下:
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏