Spring:如何在 @RestController 中返回 base64 图像

huangapple go评论134阅读模式
英文:

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 = &quot;*&quot;, maxAge = 3600)
@RestController
@Validated
public class TestController {

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

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

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

	}
}

this is my html

&lt;html&gt;
 &lt;body&gt;
   &lt;img src=&quot;http://localhost:8080/myProject/image/test&quot;/&gt;
 &lt;body/&gt;
&lt;/html&gt;

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 = &quot;/image&quot;, method = RequestMethod.GET)
	public byte[] getImage() {
		String base64 = &quot;&lt;BASE64 STRING WITHOUT `data:image/png;base64,` part&gt;&quot;;
		byte[] decodeBase64 = Base64.decodeBase64(base64);

		return decodeBase64;
	}

And your html will remain intact.

&lt;html&gt;
&lt;body&gt;
&lt;img src=http://localhost:8080/image /&gt;
&lt;body/&gt;
&lt;/html&gt;

huangapple
  • 本文由 发表于 2020年7月28日 08:42:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63125514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定