package service import ( "encoding/base64" "encoding/json" "fmt" "github.com/tidwall/gjson" "io/ioutil" "net/http" "strings" ) type BaiduOCR struct { API_KEY, SECRET_KEY string } func (this *BaiduOCR) OCR(imgBase64 string) (string, error) { url := "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + this.GetAccessToken() // image 可以通过 GetFileContentAsBase64("C:\fakepath\微信图片_20240430171848.jpg") 方法获取,如需转码请使用 url.QueryEscape() payload := strings.NewReader("image=" + imgBase64) client := &http.Client{} req, err := http.NewRequest("POST", url, payload) if err != nil { return "", err } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("Accept", "application/json") res, err := client.Do(req) if err != nil { return "", err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return "", err } words := gjson.Get(string(body), "words_result").Array() result := "" for _, word := range words { result += word.Get("words").String() } return result, nil } func (this *BaiduOCR) GetAccessToken() string { url := "https://aip.baidubce.com/oauth/2.0/token" postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", this.API_KEY, this.SECRET_KEY) resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(postData)) if err != nil { fmt.Println(err) return "" } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return "" } accessTokenObj := map[string]any{} _ = json.Unmarshal([]byte(body), &accessTokenObj) return accessTokenObj["access_token"].(string) } /** * 获取文件base64编码 * @param string path 文件路径 * @return string base64编码信息,不带文件头 */ func GetFileContentAsBase64(path string) string { srcByte, err := ioutil.ReadFile(path) if err != nil { fmt.Println(err) return "" } return base64.StdEncoding.EncodeToString(srcByte) }