简体   繁体   中英

How to properly display MJPEG snapshot from CCTV in PHP

I have a IP CCTV camera which support MJPEG. I would like to display image in HTML (from PHP script) together with other data.

I know that I can get a screenshot from the camera using:

http://username:password@<servername>/Streaming/channels/1/picture

however when I am using this simple html code image is not always displayed:

<html>
  <body>
    <IMG id="myImage" SRC='http://username:password@192.168.0.20/Streaming/channels/1/picture'>
  </body>
</html>

On Microsoft Edge, it is not possible even to login to camera. On Firefox works fine. On Chrome camera is logged however image is not displayed.

So the question is how I can get image in HTML or better in PHP to display it on the page. I prefer to use PHP because I want to add more data to page, like temperature etc.

Also will be nice to refresh the image, but this can be done in AJAX later.

Use a second PHP script to retrieve the image and point the <img> tag to that. It's possibly because the page you're displaying the image on uses HTTPS while the camera only supports HTTP. Proxying through PHP will allow it all to appear to come from the same source and PHP will handle the HTTP authentication, which will avoid any of your browser compatibility problems.

<IMG id="myImage" SRC='currentimage.php'>

currentimage.php:

<?php
$crl = curl_init('http://<servername>/Streaming/channels/1/picture');
curl_setopt($crl, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($crl, CURLOPT_USERPWD, 'username:password');
curl_setopt($crl, CURLOPT_RETURNTRANSFER, TRUE);
$contents = curl_exec($crl);
curl_close($crl);

header("Content-Type: image/jpeg");
echo $contents;
?>

To save on server load and allow it to handle more traffic, you could also cache the last-retrieved image to a file for 5-10 seconds, but that's a separate problem to solve.

This code seems to work fine for me:

<?php
while (@ob_end_clean()); 
    header('Content-type: image/jpeg'); 
// create curl resource 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_USERAGENT, $useragent); 
curl_setopt($ch, CURLOPT_URL, 'http://<servername>/Streaming/channels/1/picture'); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_USERPWD, 'username:password'); 
// $output contains the output string 
$output = curl_exec($ch); 
echo $output; 
// close curl resource to free up system resources 
curl_close($ch); 
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM