【问题标题】:PHP Azure OCR - use local filePHP Azure OCR - 使用本地文件
【发布时间】:2018-02-14 22:52:54
【问题描述】:

我正在使用 Azure OCR 服务来取回图像的文本( https://docs.microsoft.com/de-de/azure/cognitive-services/Computer-vision/QuickStarts/PHP)。

到目前为止,一切都已启动并运行,但现在我想使用本地文件而不是已经上传的文件。

$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
// Request body
$request->setBody("{body}");  // Replace with the body, for example, "{"url": "http://www.example.com/images/image.jpg"}

不幸的是,我不知道如何将原始二进制文件作为我在 PHP 中的 POST 请求的主体传递。

【问题讨论】:

    标签: php azure post request ocr


    【解决方案1】:

    首先,当我们引用本地文件时,我们应该在header中使用'Content-Type': 'application/octet-stream',然后我们可以发送使用流资源作为body的请求。

    这是我使用Guzzle 的工作代码供您参考:

    <?php
    
    require 'vendor/autoload.php';
    
    $resource = fopen('./Shaki_waterfall.jpg', 'r');
    
    $client = new \GuzzleHttp\Client();    
    $res = $client->request('POST', 'https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze', [
        'query' => [
            'visualFeatures' => 'Categories',
            'details' => '',
            'language' => 'en'
        ],
        'headers' => [
            'Content-Type' => 'application/octet-stream',
            'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>'
        ],
        'body' => $resource 
    ]);
    
    echo $res->getBody();
    

    使用HTTP_Request2

    <?php
    
    require_once 'HTTP/Request2.php';
    
    $request = new Http_Request2('https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze');
    $url = $request->getUrl();
    
    $headers = array(
        'Content-Type' => 'application/octet-stream',
        'Ocp-Apim-Subscription-Key' => '<Ocp-Apim-Subscription-Key>',
    );
    $request->setHeader($headers);
    
    $parameters = array(
        'visualFeatures' => 'Categories',
        'details' => '',
        'language' => 'en',
    );
    $url->setQueryVariables($parameters);
    
    $request->setMethod(HTTP_Request2::METHOD_POST);
    $request->setBody(fopen('./Shaki_waterfall.jpg', 'r'));  
    
    try {
        $response = $request->send();
        echo $response->getBody();
    
    } catch (HttpException $ex) {
        echo $ex;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-23
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 2019-08-02
      • 2020-10-22
      相关资源
      最近更新 更多