以下是使用 Go 实现将图片转换成 Base64 编码并在 Web 页面中显示的示例代码:
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// 读取图片文件
imageFile, err := ioutil.ReadFile("image.jpg")
if err != nil {
fmt.Println("Failed to read file:", err)
return
}
// 将图片文件转换成 Base64 编码
encodedImage := base64.StdEncoding.EncodeToString(imageFile)
// 定义 HTML 模板字符串
htmlTemplate := `
<!DOCTYPE html>
<html>
<head>
<title>Base64 Image Example</title>
</head>
<body>
<img src="data:image/jpeg;base64,%s"/>
</body>
</html>
`
// 使用 HTML 模板字符串构建 HTML 页面
htmlPage := fmt.Sprintf(htmlTemplate, encodedImage)
// 启动 HTTP 服务器并返回 HTML 页面
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprintf(w, htmlPage)
})
fmt.Println("Server started at: http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
在这个示例中,我们首先使用 ioutil.ReadFile 函数读取名为 image.jpg 的图片文件。然后,我们将文件内容使用 base64.StdEncoding.EncodeToString 函数转换成 Base64 编码的字符串。
接下来,我们定义了一个 HTML 模板字符串,其中包含一个 img 标签,指定了 src 属性为 Base64 编码的图片数据。我们使用 fmt.Sprintf 函数将 Base64 数据插入到模板字符串中,形成最终的 HTML 页面。
最后,我们启动了一个 HTTP 服务器,并在请求 / 路径时返回我们构建的 HTML 页面。当我们访问 http://localhost:8080 时,就可以看到显示了图片的网页。




