'How to create a video stream from a single dynamic image in PHP
I have a single image file on my server which its content changes every 100 ms.
I can load and serve this image as usual:
$image = file_get_contents('path/to/image.jpg');
header('Content-type: image/jpeg');
echo $image;
<img src="image.php">
Thus, every time the user updates the screen (pressing F5 for example) the server would reply a different image. I can also use Java Script (using setInterval
for example) to update the image continuously so the users needn't to update the screen themselves.
However, I need to serve this image as a CONTINUOUS FLOW such as a LIVE VIDEO STREAM in order to be shown as an HTML5 video instead of a static image.
Some examples I`ve found so far use PHP-FFMpeg library for stream videos. It turns out that those examples require that I have a video file at hand (a file in the OS or a URL to a file) instead of a single (dynamic) image as I've described above.
I found this example for how to use PHP to streaming. It looks promisssing. But again the code supposes I have a video file url which I haven't.
I'm wondering if is it possible to adapt this code to my needs. For example, how to adapt the setHeader()
method to the scenario where there are no begin and end? And considering that I have loaded the image contents using file_get_contents
or so, how to change stream()
properly? Or, at other hand, is there other way to serve this image as a video stream?
Solution 1:[1]
Well, I just found a solution for my needs:
$identifier = "an_identifier";
//set headers
header('Accept-Range: bytes');
header('Connection: close');
header('Content-Type: multipart/x-mixed-replace;boundary=' . $identifier);
header('Cache-Control: no-cache');
// loop to continuously serve an image
while(true) {
$image = load_image_contents();
echo "--" . $identifier . "\r\nContent-Type: image/jpeg\r\nContent-Length: ".strlen($image)."\r\n\r\n".$image;
flush();
usleep(50000);
}
On the browser side I just set a regular image tag:
<img src="image.php">
Solution 2:[2]
The code below should reload the image ever 200 ms. Adding a random number avoids any potential caching which is unlikely since you are requesting a PHP page.
<html>
<header>
<script>
function ReloadImage()
{
var image_element = document.getElementById('image_id');
image_element.src = 'image.php?rand=' + Math.random();
}
setInterval(ReloadImage,200);
</script>
</header>
<body>
<img src="image.php" id="image_id">
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Duloren |
Solution 2 | Markus Schumann |