解释以“多部分响应-MultiPartBoundary” API监视摄像机的格式发送响应的图像

时间:2019-02-06 00:12:44

标签: php rest api camera

我正在使用一个Surveillance Camera API,它显示实时图像,并且文档说答案是多部分响应格式,其中每个JPEG图像前都有一个标签“-MultiPartBoundary”,但我不确定如何在浏览器中解释这些图像的返回。

<?php

$Cookie = (dirname(__FILE__) . "/cookie.txt");


/*
* PRIMEIRA REQUISIÇÃO, RECEBE O COOKIE PARA O DOMINIO
*/
$curl = curl_init();

curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt_array($curl, array(
    CURLOPT_VERBOSE        => true,
    CURLOPT_PORT           => '8000',
    CURLOPT_URL            => 'http://camerasquadion.ddns.net:8000/mjpegstream.cgi',
    CURLOPT_COOKIEJAR      => $Cookie,
    CURLOPT_COOKIEFILE     => $Cookie,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING       => "",
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 20000,
    CURLOPT_USERPWD        => "Admin:Quadion*1234",
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST  => "GET",
    CURLOPT_HEADER         => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_FILETIME       => true,
    CURLOPT_HTTPHEADER      => array(
        "Content-Type: multipart/x-mixed-replace; boundary=MultiPartBoundary",
    ),
));


$responde  = curl_exec ($curl);

// Recupera o código HTTP retornado pela URL de destino
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

curl_close($curl);




/*
 * 2º Requisição, envio do cookie
 */
$ch = curl_init();

// Através da operação CURLOPT_COOKIEFILE estarei enviando meu COOKIE.
curl_setopt_array($ch, array(
    CURLOPT_COOKIEFILE      => $Cookie,
    CURLOPT_URL             => 'http://camerasquadion.ddns.net:8000/mjpegstream.cgi?camera=108801',
    CURLOPT_RETURNTRANSFER  => true,
    CURLOPT_HTTPHEADER      => array(
        "Content-Type: multipart/x-mixed-replace; boundary=MultiPartBoundary",
    ),
));

$response = curl_exec ($ch);

// Recupera o código HTTP retornado pela URL de destino
$httpCode2 = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

?>


<img src="data:image/jpg;base64,<?=base64_encode($response)?>">

1 个答案:

答案 0 :(得分:0)

假设您代码的CURL部分有效,并且在$ response中获得了有效的响应。

CURLOPT_RETURNTRANSFER设置将不仅返回响应正文,而且还将返回http标头。这些需要跳过才能获得响应正文。

然后,响应主体是一系列用定界符"- MultiPartBoundary"分隔的图像。您需要使用它来拆分响应正文以获取单个图像。

list(,$responseBody) = explode("\r\n\r\n", $response, 2);

$images = explode("- MultiPartBoundary", $responseBody);

foreach ($images as $image) {
    echo '<img src="data:image/jpg;base64,' . base64_encode(trim($image)) .'">';
}