通过 toDataURL,将图片转化为 base64,结果为 dataUrl,去掉编码头 data:image/jpeg;base64, 进行 urlencode,然后使用 GM_xmlhttpRequest 进行 https 请求,提示 json 未定义,如何获取 access_token,以及如何输出最后识别的文字结果?
https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
toDataURL(
'https://i.imgur.com/GniA3wQ.png',
function(dataUrl) {
const base64Data = dataUrl.split(';base64,')[1];
var API_Key="xxxxxxxxxxxxxxxxxxxxxxxx";
var Secret_Key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//access_token 获取地址。
var getTokenUrl="https://aip.baidubce.com/oauth/2.0/token";
var token_Res = GM_xmlhttpRequest({
method: "POST",
url: getTokenUrl,
grant_type: "client_credentials",
client_id: API_Key,
client_secret: Secret_Key,
onload: function(response){
console.log("请求成功");
console.log(response.responseText);
},
onerror: function(response){
console.log("请求失败");
}
});
var access_token = token_Res.body.json().access_token;//提示 json 未定义
//通用文字识别,50000 次 /天免费
var ocrUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
var ocr_Res = GM_xmlhttpRequest({
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
access_token: access_token,
image: "image64=" + encodeURIComponent (base64Data),
language_type:"CHN_ENG",
//data: dataUrl,
onload: function(response){
console.log("请求成功");
console.log(response.responseText);
},
onerror: function(response){
console.log("请求失败");
}
});
var json = ocr_Res.body.json();
console.log(json);
}
img 转化 base64
function toDataURL(src, callback, outputFormat) {
var img = new Image();
//img.crossOrigin = 'Anonymous';
img.crossOrigin = "";
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}