PHPとimgタグで画像の自動切り替えを行う
PHPを使ってimgタグ
の画像を自動更新することで動画風に見せるサンプル。
<html>
<head>
<title>Motion Jpeg Sample</title>
</head>
<body>
<img src="mjpeg.php" width="320" height="240">
</body>
</html>
<?php
$boundary = "myboundary";
header("Cache-Control: no-cache");
header("Cache-Control: private");
header("Pragma: no-cache");
header("Content-type: multipart/x-mixed-replace; boundary=$boundary");
print "--$boundary\n";
set_time_limit(0);
ob_implicit_flush(1);
$file = "001.jpg";
while (true) {
print("Content-type: image/jpeg\n\n");
$img = @imagecreatefromjpeg($file);
imagejpeg($img);
imagedestroy($img);
// 上記が使えない場合は下記でもOK.
//print(file_get_contents($file));
usleep(1000000);
print("--$boundary\n");
if ($file == "001.jpg") {
$file = "002.jpg";
} else {
$file = "001.jpg";
}
}
ここでは2枚の画像を1秒ごとに切り替えています。
ブラウザのリロードをしなくても画像が変わるので、上手く利用すれば、ヘッダ画像をスライドショーっぽく見せたり、更新間隔が長めの定点カメラ画像をブラウザで見たりするのに利用できそうです。