Screen capture with PHP and GD
Posted by Pierre in
Uncategorized
Tuesday, April 17. 2007
To get a snapshot of a HTML page, a window or a complete screen was always something tricky to do in PHP. For one of my current projects, I had to check that our changes did not affect visually any page. An easy way to achieve this goal is to compare the rendered pages in the browsers itself, easy and time consuming (for a human being
).
That’s why I finally sit down and implemented imagegrabscreen and imagegrabwindow . They capture respectively the whole screen or a window (using its handle).
Thanks to Edin Kadribaši?, you can fetch a 5.2.x (Threadsage build only) DLL here, simply replace the php_gd2.dll by this one (it is what will be in 5.2.2).
- Screenshot
<?php $im = imagegrabscreen(); imagepng($im,“myscreenshot.png”); ?>
- Capture a window (IE for example)
<br /> <?php <br /> $browser = new <acronym title="“InternetExplorer.Application”">COM</acronym>;<br /> $handle = $browser->HWND;<br /> $browser->Visible = true;<br /> $im = imagegrabwindow($handle);<br /> $browser->Quit(); imagepng($im, “iesnap.png”);<br /> $im = imagegrabscreen(); <br /> ?><br />
- Capture a window (IE for example) but with its content!
<?php $browser = new <acronym title="“InternetExplorer.Application”">COM</acronym>; $handle = $browser->HWND; $browser->Visible = true; $browser->Navigate(“http://blog.thepimp.net”); /* Still working? */ while ($browser->Busy) { com_message_pump(4000); } $im = imagegrabwindow($handle, 0); $browser->Quit(); imagepng($im, “iesnap.png”); ?>
- IE in fullscreen mode
$browser = new <acronym title="“InternetExplorer.Application”">COM</acronym>; $handle = $browser->HWND; $browser->Visible = true; $browser->FullScreen = true; $browser->Navigate(“http://blog.thepimp.net”); /* Still working? */ while ($browser->Busy) { com_message_pump(4000); } $im = imagegrabwindow($handle, 0); $browser->Quit(); imagepng($im, “iesnap.png”); ?>
I use Internet Explorer as example, if you like to play more with IE and com, check out the IBrowser2 documentation at MSDN. It should work with any kind of window as long as you give the correct handle (usually $obj->HWND).
- php_gd2.dll for 5.2.x thread safe build
- php gd image documentation
- IE manual (useful to tweak it from com_dotnet



