1
votes

I'm using the Azure OCR Service to get the text of an image back ( https://docs.microsoft.com/de-de/azure/cognitive-services/Computer-vision/QuickStarts/PHP).

So far everything is up and running, but now I would like to use a local file instead of an already uploaded one.

$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"}

Unfortunately I don't know how to pass the raw binary as the body of my POST request in PHP.

1

1 Answers

2
votes

At first, when we refer local file, we should use 'Content-Type': 'application/octet-stream' in a header, then we can send requests that use a stream resource as the body.

Here's my working code using Guzzle for your reference:

<?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();

Using 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;
}