PHP mjpeg 连续图片格式生成

使用PHP生产mjpeg格式图片。
在HTML直接在img的src访问。
<img src="./mjpeg2.php">

<?php

// https://github.com/donatj/mjpeg-php

date_default_timezone_set("PRC");
error_reporting(E_ALL & ~E_NOTICE);

// Used to separate multipart
$boundary = "spiderman";

// We start with the standard headers. PHP allows us this much
header("Cache-Control: no-cache");
header("Cache-Control: private");
header("Pragma: no-cache");
header("Content-type: multipart/x-mixed-replace; boundary=$boundary");

// Set this so PHP doesn't timeout during a long stream
set_time_limit(0);

$w = 400;
$h = 100;
$i = 0;
$first = true;
while(true) {
    $i++;
    
    // 加载图片
    $im = imagecreatefromjpeg("./cache/1.jpg");
    //$im = imagecreatetruecolor($w, $h);
    $fill_color = imagecolorallocate($im, 255, 255, 255);
    imagefill($im,1,1,$fill_color);
    
    // 写字
    $text_color = imagecolorallocate($im, 0, 0, 0);
    imagestring($im, 7, 5, 5,  $i . '# ' . date('Y-m-d H:i:s'), $text_color);
    
    // 绘制方框
    $fill_color = imagecolorallocate($im, 0, 255 - $i * 2, $i * 2);
    imagefilledrectangle($im, 10, 50, 30 + $i * 2, 70, $fill_color);
    // 注意:当未加载图片时,方框宽度大于200时就不显示了。

    ob_start();
    echo "--$boundary
";
    echo "Content-type: image/jpeg

";
    imagejpeg($im);
    imagedestroy($im);
    echo ob_get_clean(); 
    
    flush();
    
    // 空图片 ???当未加载图片时,不知道为什么,不添加空图片会导致图片不连续
    // $im = imagecreatetruecolor($w, $h);
    // ob_start();
    // echo "--$boundary
";
    // echo "Content-type: image/jpeg

";
    // imagejpeg($im, null, 1);
    // imagedestroy($im);
    // echo ob_get_clean();
    // flush();
    
    // 延迟
    usleep($first ? 0 : 1000000);
    $first = false;

    if($i==99)$i=0;
}

欢迎转载,转载请注明:转载自[ http://www.cnblogs.com/zjfree/ ]
原文地址:https://www.cnblogs.com/zjfree/p/14437301.html