如何从id获取二维码?

How to get QR code from id?

在我的控制器中,我有以下方法:

import net.glxn.qrgen.QRCode;
import org.marcio.demospringboot.dao.FormationRepository;
import org.marcio.demospringboot.model.Formation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.io.ByteArrayOutputStream;
import java.util.Map;

@Controller
public class FormationController {

@Autowired
private FormationRepository formationRepository;

@RequestMapping (value="formation/qr/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> qr(@PathVariable final Long id) {

    ByteArrayOutputStream stream = QRCode.from(formationRepository.findOne(id).toString()).stream();

    byte[] bytes = stream.toByteArray();

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);

    return new ResponseEntity<byte[]> (bytes, headers, HttpStatus.CREATED);
}
}

在我的 html 页面中:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>QR Code</title>
</head>
<body>

   <img th:src="@{/formation/qr/${id}}" />

</body>
</html>

这是生成的图像:

我想从您的 "id" 获取用户数据。我正在使用一个简单的存储库 Spring formationRepository 和库 net.glxn.qrgen.QRCode。该应用程序可以运行,但不会生成带有关于 "id" 的用户数据的 QR 码。谢谢。

形成前忘记'/'@RequestMapping (value="/formation/qr/{id}", method = RequestMethod.GET)

编辑:

ByteArrayOutputStream stream = QRCode.from(formationRepository.findOne(id).toString()).stream();
byte[] data = stream.toByteArray();;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentLength(data.length);

return new HttpEntity<byte[]>(data, headers);

这应该按顺序工作,以便浏览器理解它是一张图片并显示它

感谢您的帮助和意见。他们都非常乐于助人。我可以通过升级到:

来解决问题
@RequestMapping (value="/formation/qr/{id}", method = RequestMethod.GET)
public HttpEntity<byte[]> qr(@PathVariable Long id) {
    byte[] bytes = QRCode.from(formationRepository.findOne(id).getTheme()
                   .toString()).withSize(120, 120).stream().toByteArray();
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);
    headers.setContentLength(bytes.length);
    return new ResponseEntity<byte[]> (bytes, headers, HttpStatus.CREATED); 
}

解决方案是 byte []bytes = QRCode.from(formation Repository.findOne (id).getTheme()。于是就得到了注册内容(getTheme),并以二维码的形式呈现出来。