SpringBoot 与 ZXing 完美结合,轻松生成二维码!
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
@RestController
public class QrCodeController {
@GetMapping("/generateQrCode")
public RedirectView generateQrCode(HttpServletResponse response) throws WriterException, IOException {
String content = "Hello, World!";
int width = 200;
int height = 200;
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath("qrcode.png");
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
RedirectView redirectView = new RedirectView();
redirectView.setUrl("/qrcode.png");
return redirectView;
}
}
这段代码使用Spring Boot和ZXing库生成二维码图片,并将其保存到服务器上。然后通过一个重定向视图将其提供给客户端。这是一个简单的示例,展示了如何将这两个库在Spring Boot应用程序中配合使用。
评论已关闭