我拥有在Behat自动化上使用的PHP函数,该函数获取页面元素的屏幕截图并裁剪图像:
protected function takeElementScreenshot($filename, $folder, $selector)
{
$element = $this->findElement($selector);
$driver = $this->getSession()->getDriver();
$this->iScrollToTheElement('top', $selector);
$previousWindowHeight = $driver->evaluateScript("window.outerHeight");
$previousViewportHeight = $driver->evaluateScript("window.innerHeight");
$domElement = "document.evaluate(\"$selector\", document, null," .
"XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue";
$elementRect = $driver->evaluateScript("$domElement.getBoundingClientRect()");
if ($previousViewportHeight < $elementRect["height"]) {
$windowWidth = $driver->evaluateScript("window.outerWidth");
$offset = $previousWindowHeight - $previousViewportHeight;
$this->iSetBrowserWindowSizeToX($windowWidth, $elementRect["height"] + $offset);
}
$elementRect = $driver->evaluateScript("$domElement.getBoundingClientRect()");
$x = $elementRect["left"];
$y = $elementRect["top"];
$elementWidth = $elementRect["width"];
$elementHeight = $elementRect["height"];
$this->saveScreenshot($filename, $folder);
$screenshot = new Imagick("$folder/$filename");
$imageWidth = $screenshot->getimagewidth();
$imageHeight = $screenshot->getimageheight();
$cropWidth = min($imageWidth - $x, $elementWidth);
$cropHeight = min($imageHeight - $y, $elementHeight);
$screenshot->cropimage($cropWidth, $cropHeight, $x, $y);
$screenshot->writeImage("$folder/$filename");
if ($windowWidth) {
$this->iSetBrowserWindowSizeToX($windowWidth, $previousWindowHeight);
}
}
问题在于,当裁剪时,有时裁剪效果并不理想。我将花费很长时间来解释发生的情况,因此我将直接回答这个问题:如果裁剪后,有没有办法从边框中删除X像素?
示例:如果它拍摄了一个元素的屏幕截图并且结果图像为500x500,我希望它从边界处裁剪2个像素,从而得出498x498像素的图像。我不确定像素数量是否足够,所以我将对其进行测试,直到找到一个好的值。