package main
import (
"encoding/json"
"encoding/base64"
"crypto/md5"
"io/ioutil"
"io"
"strconv"
"time"
"fmt"
"net/http"
"net/url"
"strings"
//"bufio" //缓存IO
"os"
"bytes"
)
/**手写文字识别WebAPI接口调用示例接口文档(必看):https://doc.xfyun.cn/rest_api/%E6%89%8B%E5%86%99%E6%96%87%E5%AD%97%E8%AF%86%E5%88%AB.html
*图片属性:jpg/png/bmp,最短边至少15px,最长边最大4096px,编码后大小不超过4M,识别文字语种:中英文
*webapi OCR服务参考帖子(必看):http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=39111&highlight=OCR
*(Very Important)创建完webapi应用添加服务之后一定要设置ip白名单,找到控制台--我的应用--设置ip白名单,如何设置参考:http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=41891
*错误码链接:https://www.xfyun.cn/document/error-code (code返回错误码时必看)
*@author iflytek
*@RemixBy KC
*/
func ocr_handwriting() {
// 应用APPID(必须为webapi类型应用,并开通手写文字识别服务,参考帖子如何创建一个webapi应用:http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481)
appid := "*Fix me"
// 接口密钥(webapi类型应用开通手写文字识别后,控制台--我的应用---手写文字识别---相应服务的apikey)
apikey := "*Fix me"
curtime := strconv.FormatInt(time.Now().Unix(), 10)
param := make(map[string]string)
//FilePath
filename := "2.jpg"
filepath:="./"+filename
// 语种参数和文本位置参数
param["language"] = "en"
param["location"] = "true"
tmp, _ := json.Marshal(param)
base64_param := base64.StdEncoding.EncodeToString(tmp)
w := md5.New()
io.WriteString(w, apikey+curtime+base64_param)
checksum := fmt.Sprintf("%x", w.Sum(nil))
// 测试图片地址
f, _ := ioutil.ReadFile(filepath)
f_base64 := base64.StdEncoding.EncodeToString(f)
data := url.Values{}
data.Add("image", f_base64)
body := data.Encode()
client := &http.Client{}
// 手写文字识别OCR接口地址
req, _ := http.NewRequest("POST", "http://webapi.xfyun.cn/v1/service/v1/ocr/handwriting", strings.NewReader(body))
req.Header.Set("X-Appid", appid)
req.Header.Set("X-CurTime", curtime)
req.Header.Set("X-Param", base64_param)
req.Header.Set("X-CheckSum", checksum)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, _ := client.Do(req)
defer res.Body.Close()
res_body, _ := ioutil.ReadAll(res.Body)
fmt.Print(string(res_body))
/*Indent*/
var out bytes.Buffer
err := json.Indent(&out, res_body, "", "\t")
if err != nil {
fmt.Print("err")
}
/*Create*/
writeToFile(string(out.Bytes()), filename)
}
func main() {
ocr_handwriting()
}
func writeToFile(msg string, filename string) {
filePath := "./result_"+filename+".txt"
f, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Println(err.Error())
}
_, err = f.Write([]byte(msg))
if err != nil {
fmt.Println(err.Error())
}
f.Close()
}
代码下载
https://download.csdn.net/download/ScarletMeCarzy/12873724