Wednesday, September 12, 2012

Screenshots With PHP (GD2)

Found this neat technique to grab a screenshot of a window using PHP, and after some debugging, I was finally able to get it to work.

Here's how:

Note: I believe this only works on windows boxes. If I find a method for a Linux machine, I'll be sure to write something on that as well.

<?php

$browser 
= new COM("InternetExplorer.Application");
$handle $browser->HWND;
$browser->Visible true;
$browser->Navigate("http://www.libgd.org");

/* Still working? */

while ($browser->Busy
{
    
com_message_pump(4000);
}


$im imagegrabwindow($handle0);
$browser->Quit();

imagepng($im"iesnap.png");
imagedestroy($im);

?>

Running just this script alone won't get you the screenshot. You need to go into Windows services and allow whatever web server you are running to interact with the desktop. (If you do not do the below... the images will save as a black filled png file.)

To do this...

Right click 'My Computer' and click Manage.


Find the web server's service (I am using WAMP Server for this demonstration), right click it and hit properties.

Click the 'Log On' tab and check the 'Allow service to interact with desktop' box.

Restart Apache and you should now be able to use the above script. 


Oh, and if you want the image to not have the nasty Internet explorer scroll bars / menus add this to the script:

$browser->Fullscreen = true;

Script credits goes to: http://www.php.net/manual/en/function.imagegrabwindow.php