另一种使用 PHP 截取屏幕截图而不需要任何额外服务器资源的方法是使用 Google 的PageSpeed Insights API,它不需要任何类型的任何身份验证。它现在是免费且开放的,所以请利用它。
相同的实现细节在这里:Generating Screenshots of URLs using Google's secret magic API。
源代码
<?php
// Creating a proxy to use GET request to hit the Google Page Speed API and receive a screenshot.
// Check if the URL parameter for our proxy is set.
if (!empty($_GET['url'])) {
// Make sure the given value is a URL.
if (filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
// Hit the Google PageSpeed Insights API.
// Catch: Your server needs to allow file_get_contents() to make this run. Or you need to use cURL.
$googlePagespeedResponse = file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?screenshot=true&url={$_GET['url']}");
// Convert the JSON response into an array.
$googlePagespeedObject = json_decode($googlePagespeedResponse, true);
// Grab the Screenshot data.
$screenshot = $googlePagespeedObject['screenshot']['data'];
// Replace Google's anamolies.
$screenshot = str_replace(array('_','-'), array('/','+'), $screenshot);
// Build the Data URI scheme and spit out an <img /> Tag.
echo "<img src=\"data:image/jpeg;base64,{$screenshot}\" alt=\"Screenshot\" />";
} else {
// If not a valid URL.
echo "Given URL is not valid.";
}
} else {
// URL not set.
echo "You need to specify the URL.";
}
?>
您也可以使用客户端执行此操作:
$(function () {
// Get the URL.
var url = "https://praveen.science/";
// Prepare the URL.
url = encodeURIComponent(url);
// Hit the Google Page Speed API.
$.get("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?screenshot=true&strategy=mobile&url=" + url, function (data) {
// Get the screenshot data.
var screenshot = data.screenshot;
// Convert the Google's Data to Data URI scheme.
var imageData = screenshot.data.replace(/_/g, "/").replace(/-/g, "+");
// Build the Data URI.
var dataURI = "data:" + screenshot.mime_type + ";base64," + imageData;
// Set the image's source.
$("img").attr("src", dataURI);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hard Coded Screenshot of my Website:</h1>
<img src="//placehold.it/300x50?text=Loading+Screenshot..." alt="Screenshot" />