英文:
Spring : How to return base64 image in @RestController
问题
You can try changing your HTML img tag as follows:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYIAAACzCAY...." />
Make sure to include the entire base64 image data directly in the src
attribute of the img tag. This should display the base64 image correctly in your HTML.
英文:
I have base64 String and I want to print base64 image on img tag using Spring's restcontroller.
I'm developing the front and the back separately.
this is my restcontroller
@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;
}
}
this is my html
<html>
<body>
<img src="http://localhost:8080/myProject/image/test"/>
<body/>
</html>
The image is not output. What's the problem?
答案1
得分: 2
你已经快完成了,只需从字符串中删除data:image/png;base64,
部分。这是因为你在img src
中使用的是字节而不是base64字符串。
@RequestMapping(value = "/image", method = RequestMethod.GET)
public byte[] getImage() {
String base64 = "<BASE64字符串,去除`data:image/png;base64,`部分>";
byte[] decodeBase64 = Base64.decodeBase64(base64);
return decodeBase64;
}
而你的HTML代码将保持不变。
<html>
<body>
<img src=http://localhost:8080/image />
<body/>
</html>
英文:
You are almost there, just remove data:image/png;base64,
part from your string. This is because you are using bytes and not base64 string in your 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;
}
And your html will remain intact.
<html>
<body>
<img src=http://localhost:8080/image />
<body/>
</html>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论