有很多开源项目可以生成网站截图和缩略图,可以从PHP调用。例如phantomjs、webkit2ping等
这些项目的最大问题是,它们基于较旧的浏览器技术,并且在呈现许多站点时存在问题,尤其是在过去几个月/年中使用WebFonts、FlexBox、SVG和各种其他添加到HTML5和CSS规范中的站点。
我尝试过一些第三方服务,大多数是基于Phantomjs的,这意味着它们也会产生质量较差的截图。生成网站截图的最佳第三方服务是
urlbox.io
. 这是一项付费服务,尽管有一个免费的7天试用期来测试它,而不承诺任何付费计划。
Here is a link to the documentation
下面是让它在PHP中与Composer一起工作的简单步骤。如果不使用composer,只需从
github repo
// 1 . Get the urlbox/screenshots composer package (on command line):
composer require urlbox/screenshots
// 2. Set up the composer package with Urlbox API credentials:
$urlbox = UrlboxRenderer::fromCredentials('API_KEY', 'API_SECRET');
// 3. Set your options (all options such as full page/full height screenshots, retina resolution, viewport dimensions, thumbnail width etc can be set here. See the docs for more.)
$options['url'] = 'http://stackoverflow.com/questions/4235638/how-to-take-thumbnail-screenshots-of-websites-using-php'; // set url to this very page!
$options['thumb_width'] = 400; // set thumbnail to be 400px wide
$options['full_page'] = true; // set full_page mode on, will instruct urlbox to take a full height screenshot
// 4. Generate the Urlbox url
$urlboxUrl = $urlbox->generateUrl($options);
// $urlboxUrl is now 'https://api.urlbox.io/v1/ca482d7e-9417-4569-90fe-80f7c5e1c781/0ad1be1ff7ac16bc295d8b0207c98e776003e53e/png?url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F4235638%2Fhow-to-take-thumbnail-screenshots-of-websites-using-php&full_page=true&thumb_width=400'
// 5. Now stick it in an img tag, when the image is loaded in browser, the API call to urlbox will be triggered and a nice PNG screenshot will be generated!
例如,这里有一个urlbox url,它将生成这个页面的全高截图:
下面是最终的屏幕截图(通过imgur/严重压缩)