Single Frame Capturing Using PHP
Submitted by John Huong
Introduction
This PHP script is a port of the original MJ-Grab program.
Detailed Description
To use this PHP script just copy and paste the PHP code listed into a file(let's say pmjgrab.php) and place it into the appropriate folder. Next change the variable $host and $port according to your respective Motion setup. Once that is done, just add the following HTML code to your page.
<IMG SRC ='/pmjgrab.php'>
if you look through the code, by default I generate an image of the size 352X288, you can modify this to your hearts content my changing the parameter for the first call to the imagecreatetruecolor function.
My code also has the option of generating a thumbnail by using the following HTML code
<IMG SRC ='/pmjgrab.php?thumb=1'>
Size of thumbnail can be adjusted by adjusting the parameters of the second reference to imagecreatetruecolor function.
Code
<?
imagejpeg(LoadJpeg());
exit;
function LoadJpeg ()
{
$filearray= array();
$i = 0;
$host = '127.0.0.1';
$port='9191';
$handle = fopen("http://$host:$port/", "rb"); //ensure opens binary
$response = fgets($handle,70);
while(strncmp($response,"Content-Length:",15)!=0)
{
$response= fgets($handle, 70);
}
$jpglength = substr($response,15);
trim($jpglength);
$response= fgets($handle, 70);
$readtimes = floor($jpglength/2048);//php only reads one packet at a time regardless of size specification... this assumes one packet is 2K in size.
$packetsize = 2048;
$lengthremainder = 0;
if ($readtimes == 0)
{
$packetsize = $jpglength;
}
else
{
$lengthremainder = $jpglength%2048;
}
$jpgfile = '';
for ($i=0;$i <$readtimes; $i++)
{
$jpgfile .= fread($handle,$packetsize);
}
if ($readtimes == 0)
{
$jpgfile .= fread($handle,$packetsize);
}
else
{
$jpgfile .= fread($handle,$lengthremainder);
}
fclose($handle);
$im = imagecreatetruecolor ( 352, 288);
if ($imgfile != 'none')
{
$img = @imagecreatefromstring($jpgfile);
if ($img == '')
{
$tc = imagecolorclosest($im, 255, 255, 255);
imagestring ($im, 1, 5, 5, "Webcam: HELP! I've either crashed or been given the Alt-F4!", $tc);
}
else
{
$im = $img;
}
}
else
{
$tc = imagecolorclosest($im, 255, 255, 255);
imagestring ($im, 1, 5, 5, "Webcam: HELP! I've either crashed or been given the Alt-F4!", $tc);
}
if (isset($_GET['thumb']))
{
$thumbimg = imagecreatetruecolor ( 176, 144);
imagecopyresampled($thumbimg,$im,0,0,0,0,imagesx($thumbimg),imagesy($thumbimg),imagesx($im),imagesy($im));
return $thumbimg;
}
return $im;
}
?>