我有以下实现来创建 QR 码并尝试将生成的代码作为 html 响应返回(要求用户打开或保存生成的图像),而不是保存到目录中的文件。然而,我无法做到这一点。我在 Baeldung 上使用以下示例:https://www.baeldung.com/java-generate-barcodes-qr-codes
public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception {
QRCodeWriter barcodeWriter = new QRCodeWriter();
BitMatrix bitMatrix =
barcodeWriter.encode(barcodeText, BarcodeFormat.QR_CODE, 200, 200);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
我使用以下 REST 控制器方法:
@RestController
@RequestMapping("/barcodes")
public class BarcodesController {
@GetMapping(value = "/barbecue/ean13/{barcode}", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<BufferedImage> barbecueEAN13Barcode(@PathVariable("barcode") String barcode)
throws Exception {
return okResponse(BarbecueBarcodeGenerator.generateEAN13BarcodeImage(barcode));
}
//...
}
但是,我无法获取图像作为 HTTP 响应。那么,我该如何解决呢?
更新:这是我的Application.java:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args)
}
@Bean
public HttpMessageConverter<BufferedImage> createImageHttpMessageConverter() {
return new BufferedImageHttpMessageConverter();
}
}
够了吗?或者我应该从任何地方调用它?
下次请标记为已解决。