Modify Php function to crop image border by X pixels
Modify Php function to crop image border by X pixels
I have this PHP function that I use on Behat automation which takes a screenshot of an element of the page, cropping the image:
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);
}
}
The problem is that when it crops, sometimes it does not crop perfectly. I would take a long time to explain what happens so I will go direct to the question: Is there a way to remove X pixels from the borders after if crops?
Example: if it takes a screenshot of an element and the result image is 500x500, I would like it to crop 2 pixels from the borders, resulting in an image of 498x498 pixels. The pixel amount I'm not sure yet how much it will be enough, so I will test it until I find a good value.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Comments
Post a Comment