ZBLOG

golang 实现 web base64图片

以下是使用 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 时,就可以看到显示了图片的网页。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=2320

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?