golang 将图片生成Base64

臭大佬 2023-10-16 17:17:08 1283
Go 
简介 golang 将图片生成Base64

代码

package main

import (
    "encoding/base64"
    "errors"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "os"
    "strings"
    "time"
)

// GetUrlImgBase64 golang 将图片生成Base64
func GetUrlImgBase64(path string) (baseImg string, err error) {
    imgByte := []byte{}
    if strings.Contains(path, "http") {
        //获取网络图片
        client := &http.Client{
            Timeout: time.Second * 5, //超时时间
        }
        var bodyImg io.Reader
        request, er := http.NewRequest("GET", path, bodyImg)
        if er != nil {
            err = errors.New("获取网络图片失败")
            return
        }
        respImg, _ := client.Do(request)
        defer respImg.Body.Close()
        imgByte, _ = ioutil.ReadAll(respImg.Body)
    } else {
        //获取本地文件
        file, er := os.Open(path)
        if er != nil {
            err = errors.New("获取本地图片失败")
            return
        }
        defer file.Close()
        imgByte, _ = ioutil.ReadAll(file)
    }
    // 判断文件类型,生成一个前缀,拼接base64后可以直接粘贴到浏览器打开,不需要可以不用下面代码
    //取图片类型
    mimeType := http.DetectContentType(imgByte)
    switch mimeType {
    case "image/jpeg":
        baseImg = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(imgByte)
    case "image/png":
        baseImg = "data:image/png;base64," + base64.StdEncoding.EncodeToString(imgByte)
    }
    return
}

func main() {
    i, err := GetUrlImgBase64("./avatar.jpg")
    // i, err := GetUrlImgBase64("https://www.choudalao.com/images/config/avatar.jpg")
    if err != nil {
        fmt.Printf("err :%v\n", err)
        return
    }
    fmt.Printf("i: %v\n", i)
}