Merge pull request #753 from sameira/master

BAEL-387 Print Screen In Java
This commit is contained in:
Marek Lewandowski 2016-10-18 19:53:41 +02:00 committed by GitHub
commit 2bea888ce1
3 changed files with 103 additions and 0 deletions

26
printscreen/pom.xml Normal file
View File

@ -0,0 +1,26 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>corejava-printscreen</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>How to Print Screen in Java</name>
<url>https://github.com/eugenp/tutorials</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,38 @@
package org.baeldung.corejava;;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class Screenshot {
private String filePath;
private String filenamePrefix;
private String fileType;
private int timeToWait;
public Screenshot(String filePath, String filenamePrefix,
String fileType, int timeToWait) {
this.filePath = filePath;
this.filenamePrefix = filenamePrefix;
this.fileType = fileType;
this.timeToWait = timeToWait;
}
public void getScreenshot() throws Exception {
Thread.sleep(timeToWait);
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, fileType, setupFileNamePath());
}
private File setupFileNamePath() {
return new File(filePath + filenamePrefix + "." + fileType);
}
private Rectangle getScreenSizedRectangle(final Dimension d) {
return new Rectangle(0, 0, d.width, d.height);
}
}

View File

@ -0,0 +1,39 @@
package org.baeldung.corejava;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
public class ScreenshotTest {
private Screenshot screenshot;
private String filePath;
private String fileName;
private String fileType;
private File file;
@Before
public void setUp() throws Exception {
filePath = "";
fileName = "Screenshot";
fileType = "jpg";
file = new File(filePath + fileName + "." + fileType);
screenshot = new Screenshot(filePath, fileName, fileType, 2000);
}
@Test
public void testGetScreenshot() throws Exception {
screenshot.getScreenshot();
assertTrue(file.exists());
}
@After
public void tearDown() throws Exception {
file.delete();
}
}