gin base64 转 图片 直接显示在前端

环境

  • go 1.17.1
  • gin 1.7.7

后端代码

package main

import (
	"encoding/base64"
	"github.com/gin-gonic/gin"
)

func main() {
	engine := gin.Default()

	imageBase64 := "iVBORw0KGgoAAAANSUhEUgAAAMgAAABwCAIAAADUo6jRAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAEoSURBVHhe7dJBDQAgDAAxtKBnZucQE9yvSSX03B34TiwSYpEQi4RYJMQiIRYJsUiIRUIsEmKREIuEWCTEIiEWCbFIiEVCLBJikRCLhFgkxCIhFgmxSIhFQiwSYpEQi4RYJMQiIRYJsUiIRUIsEmKREIuEWCTEIiEWCbFIiEVCLBJikRCLhFgkxCIhFgmxSIhFQiwSYpEQi4RYJMQiIRYJsUiIRUIsEmKREIuEWCTEIiEWCbFIiEVCLBJikRCLhFgkxCIhFgmxSIhFQiwSYpEQi4RYJMQiIRYJsUiIRUIsEmKREIuEWCTEIiEWCbFIiEVCLBJikRCLhFgkxCIhFgmxSIhFQiwSYpEQi4RYJMQiIRYJsUiIRUIsEmKREIuEWCTEIiEWCbEI7Dx7NR4/Zd9aZQAAAABJRU5ErkJggg=="
	imageBuffer, _ := base64.StdEncoding.DecodeString(imageBase64)

	engine.GET("/view", func(c *gin.Context) {
		_, _ = c.Writer.WriteString(string(imageBuffer))
	})

	_ = engine.Run()
}

前端代码

<html>
    <img src="http://localhost:8080/view">
</html>

效果

注意事项

  • base64 字符串一般会包含头部 data:image/xxx;base64, 需要去除
posted @ 2022-02-28 16:24  Heei  阅读(940)  评论(0编辑  收藏  举报