【问题标题】:Spring : How to return base64 image in @RestControllerSpring:如何在 @RestController 中返回 base64 图像
【发布时间】:2020-11-17 09:15:29
【问题描述】:

我有 base64 字符串,我想使用 Spring 的 restcontroller 在 img 标签上打印 base64 图像。

我正在分别开发正面和背面。

这是我的休息控制器

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@Validated
public class TestController {

    @RequestMapping(value = "/image/test",  method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] getImage() throws Exception {

        String base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYIAAACzCAY...."; //from DB

        byte[] decodeBase64 = Base64.decodeBase64(base64);
        
        return decodeBase64;

    }
}

这是我的html

<html>
 <body>
   <img src="http://localhost:8080/myProject/image/test"/>
 <body/>
</html>

图像不输出。有什么问题?

【问题讨论】:

  • 阅读“数据 URL”,然后看看您是否可以确定您需要使用该字符串的哪个部分。

标签: java html spring image base64


【解决方案1】:

你快到了,只需从你的字符串中删除data:image/png;base64, 部分。这是因为您在 img src 中使用的是字节而不是 base64 字符串。

@RequestMapping(value = "/image", method = RequestMethod.GET)
    public byte[] getImage() {
        String base64 = "<BASE64 STRING WITHOUT `data:image/png;base64,` part>";
        byte[] decodeBase64 = Base64.decodeBase64(base64);

        return decodeBase64;
    }

您的 html 将保持不变。

<html>
<body>
<img src=http://localhost:8080/image />
<body/>
</html>

【讨论】:

    猜你喜欢
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2018-06-06
    • 2023-03-29
    相关资源
    最近更新 更多