Spring : 如何在@RestController 中 return base64 图像
Spring : How to return base64 image in @RestController
我有 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>
图像未输出。有什么问题?
您快完成了,只需从您的字符串中删除 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>
我有 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>
图像未输出。有什么问题?
您快完成了,只需从您的字符串中删除 data:image/png;base64,
部分。这是因为您在 img src
.
@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>