使用PHP从URL创建缩略图

时间:2011-01-30 20:10:32

标签: php html web

我想生成网站的缩略图。我找到了一些使用API​​处理它的网站,例如http://www.websnapr.com/

如何用PHP完成这项工作,以便处理我服务器上的所有请求?

4 个答案:

答案 0 :(得分:3)

PHP不能自行完成,因为它不包含HTML呈现库。

你可以找到一种捕获屏幕截图的外部方法,并使用PHP与该方法进行通信。

首先,您需要设置一个系统来截取屏幕截图。查看IECapt(http://iecapt.sourceforge.net/),CutyCapt(http://cutycapt.sourceforge.net/)或khtml2png(http://khtml2png.sourceforge.net/)并配置其中一个系统

然后设置一个PHP脚本,该脚本将exec()截取应用程序并将数据返回给浏览器。

例如:

<?php
$in_url = 'http://' . $_REQUEST['url']; // !!INSECURE!! In production, make sure to sanitize this input!
$filename = '/var/cutycapt/images/' . $_REQUEST['url'] . '.png'; // Will probably need to normalize filename too, this is just an illustration

// First check the file does not exist, if it does exist skip generation and reuse the file
// This is a super simple caching system that will help to reduce the resource requirements
if(!file_exists($filename)) {
  exec('/usr/local/bin/CutyCapt --url="' . $_REQUEST['url'] . '" --out="' . $filename . '"');
}

// Second check if the file exists, either from a previous run or from the above generation routine
if(file_exists($filename)) {
  header('Content-type: image/png');
  print file_get_contents($filename);
} else {
  header('Status: 500 Internal Server Error');
}
?>

然后您可以通过以下方式调用脚本:

http://localhost/screenshot.php?url=www.google.com

构建屏幕截图将是CPU密集型的,因此我强烈建议构建某种文件缓存(即保存输出结果并检查是否已经在某处有截图),甚至可能是排队系统,这样您的截屏服务器就不会不堪重负。

答案 1 :(得分:1)

答案取决于您使用的平台。无论如何,这是question asked before.

如果你想创建无头(无屏幕)基于命令行的屏幕截图,大多数aproaches都以某种方式涉及Xvfb,和/或安装了很多依赖项/库。

<强>的Linux:

khtml2png.sourceforge.net

mysql-apache-php.com/website_screenshot.htm

cutycapt.sourceforge.net

www.unruhdesigns.com/news/2010/10/using-firefox-on-a-headless-server-to-make-screenshots-of-websites

<强>窗口:

iecapt.sourceforge.net

<强> MAC:

www.paulhammond.org/webkit2png /

编辑:当然,对于像rackspace这样的东西,以及任何可以编译和安装自己的代码的共享主机,比如webfaction,它不仅仅是可行的。

欢呼声

答案 2 :(得分:0)

我担心php无法单独处理这些任务。您必须在服务器上安装一些外部库。

可能相关的answer

答案 3 :(得分:0)

蒂姆可能是对的,你不能在共享主机上做类似的事情。

我已经完成的一个实现是在专用的Linux服务器上使用的,它有Xvfb,firefox和import命令。

您可能还想查看this question