For taking a screenshot in Selenium, does it support only the PNG format or will it also support the JPEG format?
Which is the default one image format for taking screenshot in Selenium and differences?
Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. It only takes a minute to sign up.
Sign up to join this communityFor taking a screenshot in Selenium, does it support only the PNG format or will it also support the JPEG format?
Which is the default one image format for taking screenshot in Selenium and differences?
Based on the Stack Overflow post that was given in a comment, you can do this with fairly easily it appears.
In that post it looks like you can use Java.awt.Robot
to create an image with pixels that are taken from the screen...a screenshot. The code that they give is:
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "jpg", new File(args[0]));
Keep in mind that this is nearly 10 year old code and will only capture the primary monitor.
The ImageIO.Write()
method takes a parameter that allows for different image formats:
ImageIO.write(capture, "jpg", new File(args[0]));
This ImageIO
takes the buffered image from the robot and writes it to a file of any format that you like.
Just change the "jpg"
to the format you want and give it a test to make sure that it works.
java.awt.Robot
.
Aug 8, 2018 at 6:33
Selenium's TakesScreenshot
interface supports only the PNG file format. Once you get the screenshot, it is trivial to convert it into JPEG using the ImageIO library.
File screenShot = (File)((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
bufferedImage = ImageIO.read(screenShot);
// Create a blank, RGB, same width and height, and a white background
BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
bufferedImage.getHeight(),
BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
// Write to a JPEG file
ImageIO.write(newBufferedImage, "jpg", new File("JPGFilePath.jpg"));
Using TakesScreenshot interface as suggested by Aulis you can easily capture the screen.
Usage:
screenShot = (File)((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
screenShot.renameTo(new File(outputPath, String.format("%s.jpg", "screenshot")));
I believe you should be able to easily change the extension here to get a jpg as well. An advantage of choosing this over Robot is that when you're executing your code on a remote VM Robot will not work whereas this one will. Hope this helps.