2009年12月1日 星期二

[PHP] Motion JPEG - MJPEG/MJPG HTTP streaming

當你有一串連續的 JPEG 圖片時,想串成影片該怎麼辦呢?


因為工作上的需要,稍稍研究一下,從 Motion JPEG - Wikipedia, the free encyclopedia 可以看到關於 M-JPEG over HTTP 的簡介,於是我又試了一下。


PHP 搭配 Apache Web Server 範例:


@img_show.php
<?php
$boundary = 'ca3cdghdujhihal3';
$delay = 1;

header( "Content-Type: multipart/x-mixed-replace; boundary=\"$boundary\"\r\n" );

echo "--$boundary\n" ;

for( $i=1 ; $i<= 10 ; $i++ )
{
        echo 'Content-Type: image/jpeg'."\n\n";

        echo file_get_contents( "/path/images/$i.jpg" );

        echo "\n--$boundary\n" ;

        flush();
        sleep( $delay );
}
?>



此例將會依序呈現出 /path/images/1.jpg ~ /path/images/10.jpg 這些圖片囉,只是很可惜的,IE瀏覽器尚不支援,我在 IE8 也還是不會動。


可以直接用 Firefox 去瀏覽 http://host/path/img_show.php 看到成果,或是用 <img src="http://host/path/img_show.php" /> ,只是 HTML 部份我在 Ubuntun 9.04 + Firefox Shiretoko 3.5.5 此 img tag 並不會看到效果,但在 Windows XP with SP3 + Firefox 3.5.5 倒是正常。


另外,可以再參考 Cambozola Streaming Image Viewer ,這是一個 Java 版 Server Socket 範例,其 source code 中,可以在 src/com/charliemouse/cambozola/server 看到 MJPEG Streaming Server 的範例程式,只需要將該目錄下的 testImages 和 TestServer.java 複製出來,前者是照片的來源,後者是程式,接著把 TestServer.java 最上面的 package 定義清掉,再拿掉 AppID 的部份,基上就變成很簡單的 java code 啦,編譯完執行它,預設在 port 2020  開啟此服務,接著一樣用 http://localhost:2020/ 就會看到動畫效果囉。


沒有留言:

張貼留言