php之使用file_get_contents对百度orc进行文字识别(二维码识别同理)--base64编码方式(解决image format error)

参考资料:

获取Access Token:https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu

百度ocr参考手册:https://cloud.baidu.com/doc/OCR/s/zk3h7xz52

将图片转换base64编码:https://blog.csdn.net/weixin_44797182/article/details/105922765

php之使用curl对百度orc进行文字识别(二维码识别同理)–base64编码方式(解决image format error):https://blog.csdn.net/weixin_44797182/article/details/105925995

代码实例:

直接把最后的实例放到最上面了,也方便自己查阅,不过劝各位还是不要使用手册上的呢个方式,我试了,会报错 image format error ; 复制下面代码,修改api key和secret key就行,其实就是两次post请求
  第一次:获取Access Token;参数是API Key;API Key;
  第二次:对图片就行文字识别;参数是图片链接;分两种:链接导入,base64导入

<?php
header('Content-type:text/html;charset=utf-8');

// 1,获取Access Token
$url = 'https://aip.baidubce.com/oauth/2.0/token';
// 相当于URl的参数
$data = array(
    'grant_type' => 'client_credentials',//必须参数,直接这样写就行
    'client_id' => '1111', //必须参数,应用的API Key;
    'client_secret' => '222' //必须参数,应用的API Key;;
);
$token_result = json_decode(query_post($url, $data));     // 对返回的json数据进行转换
$token = $token_result->access_token;              //获取Access Token
// print_r($token);



// 2,获取图片信息
$requestImgUrl = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' . $token;
$data = array(
    // 必须得是网站上的图片,像本地上的图片进不能使用,这就是为什么要使用base64编码
    // 'url' => 'http://aip.bdstatic.com/portal/dist/1530540600796/ai_images/technology/ocr-general/general/tech-general-original-scanned.png',//你的图片地址

    // 使用base编码进行提交图片,连接或本地图片都行
    // 'image' => chunk_split(base64_encode(file_get_contents('../pic_001.png')))
    'image' => chunk_split(base64_encode(file_get_contents('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588616902312&di=4ee3454b71e4d46238dcd896e89742ab&imgtype=0&src=http%3A%2F%2Fimg1.imgtn.bdimg.com%2Fit%2Fu%3D2676471211%2C3986314344%26fm%3D214%26gp%3D0.jpg')))
);
$token_result = query_post($requestImgUrl, $data);     // 进行post请求

// print_r($token_result);     //返回json数据
print_r(json_decode($token_result));      






function query_post($url = '', $data = array())
{
    $context = stream_context_create([
        'http' => [         //以HTTP请求为键的设置数组
            'method' => "POST",  // 设置请求方法为POST
            'content' => http_build_query($data),       //建立一个url后缀,即这里相当于 ceshi=我是呢个最靓的仔
            'header'  => "Content-type: application/x-www-form-urlencoded;charset=utf-8", //通过设置头文件来设置POST数据格式
            'timeout' => 60,              //设置请求的超时时间
        ]
    ]);
    $result = file_get_contents($url, false, $context);
    return $result;
}
?>

在这里插入图片描述

使用百度ocr步骤:

在这里插入图片描述
在这里插入图片描述

获取Access Token其实还有一种方式

在搜索框中直接输入以下连接,就能直接获取,修改API Key,Secret Key;就行

https://aip.baidubce.com/oauth/2.0/token
?grant_type=client_credentials
&client_id= 你的应用的API Key
&client_secret= 应用的Secret Key;

在这里插入图片描述

posted @ 2022-04-02 09:47  coderwcb  阅读(109)  评论(0)    收藏  举报