Adding Print Screen in Java

This commit is contained in:
Sameera 2016-10-17 00:24:25 +05:30
parent 298c5e3091
commit 4db81e96b2
3 changed files with 112 additions and 0 deletions

31
printscreen/pom.xml Normal file
View File

@ -0,0 +1,31 @@
<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>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,42 @@
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() {
try {
Thread.sleep(timeToWait);
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, fileType, setupFileNamePath());
} catch (Exception ex) {
System.out.println("Error occurred while getting the Print Screen.");
}
}
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();
}
}