Notepad++Good Luck To You!

百度云ocr接口笔记

这里我们主要来看图片参数,图片参数可以通过两种方式传递:

  1. url方式

通过url传递比较简单,直接拿过来用就好,实例代码如下:

<?phpfunction request_post($url = '', $param = '', $header = []) {    if (empty($url) || empty($param)) {        return false;
    }   

    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init();//初始化curl
    curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($curl);//运行curl
    curl_close($curl);    return $data;
}

$api = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=xxxxxxx';
$image_url = 'xxx.com/a.png'; // 网络图片url$header = ['Content-Length: application/x-www-form-urlencoded'];
$post = [ 
    'url' => $image_url,
];

$res = request_post($api, $post, $header);

2、image方式

image参数需要对本地图片进行base64编码,然后进行传递,接口文档中比较坑的点:

  • Content-Type用的是multipart/form-data

  • base64编码后并不需要进行urlencode

$api = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=xxxxxxx';
$header = ['Content-Length: multipart/form-data'];

$file = '/data/image/a.png'; // 本地图片路径$image = base64_encode(file_get_contents($file));
$post = [ 
    'image' => $image,
];

$res = request_post($api, $post, $header);
«    2023年7月    »
12
3456789
10111213141516
17181920212223
24252627282930
31
TOP 搜索
TOP 控制面板
您好,欢迎到访网站!
  查看权限
TOP 最新留言
    TOP 作者列表
    TOP 站点信息
    • 文章总数:163
    • 页面总数:0
    • 分类总数:6
    • 标签总数:20
    • 评论总数:0
    • 浏览总数:312004
    召唤伊斯特瓦尔