百度ocr文字识别接口使用

最近有个需求需要识别图片中的文字,所以就用到了百度的ocr接口,结果在测试的过程中被图片格式搞的有点晕,试了好久终于成功了,在此记录一下。

附ocr接口文档地址:https://cloud.baidu.com/doc/OCR/OCR-API.html#.E8.BF.94.E5.9B.9E.E8.AF.B4.E6.98.8E

我们先来看一下接口说明:

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

  1. url方式

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

<?php
function 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);
posted @ 2018-03-07 10:31  不想上班的程序猿  阅读(26305)  评论(1编辑  收藏  举报