Difference between revisions of "Taking a Screenshot in Java"
PeterHarding (talk | contribs) |
PeterHarding (talk | contribs) |
||
(2 intermediate revisions by the same user not shown) | |||
Line 4: | Line 4: | ||
<pre> | <pre> | ||
// | // To determine the screen dimensions. | ||
Toolkit toolkit = Toolkit.getDefaultToolkit(); | Toolkit toolkit = Toolkit.getDefaultToolkit(); | ||
Line 14: | Line 14: | ||
<pre> | <pre> | ||
// | // Capture the BufferedImage with createScreenCapture() method. | ||
Robot robot = new Robot(); | Robot robot = new Robot(); | ||
Line 24: | Line 24: | ||
<pre> | <pre> | ||
// | // Save the BufferedImage to a JPG File. | ||
File file = new File(“screen.jpg”); | File file = new File(“screen.jpg”); | ||
Line 32: | Line 32: | ||
[[Category:Java]] | [[Category:Java]] | ||
[[Category:Examples]] |
Latest revision as of 11:35, 4 December 2008
Here is how to capture a screenshot and save it as a JPG file using Java. It is done using the ImageIO API for saving the screenshot as the JPG file and using the Robot class to perform the screenshot.
First the screen dimension should be worked out and then create a rectangle with these dimensions. The screen dimansions can be found using the Toolkit class. The following code snippet show how...
// To determine the screen dimensions. Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
After getting the screen dimensions, create an instance of the Robot class and copy the rectangle from the screen. The createScreenCapture() method in the Robot class can be used to get the BufferedImage with the rectangular dimension passed as argument to it. The following code snippet demonstrates how this is done...
// Capture the BufferedImage with createScreenCapture() method. Robot robot = new Robot(); BufferedImage image = robot.createScreenCapture(rectangle);
Creating the JPG file from the BufferedImage is possible using the ImageIO API to convert the BufferedImage to the JPG file. The following code snippet show how...
// Save the BufferedImage to a JPG File. File file = new File(“screen.jpg”); ImageIO.write(image, “jpg”, file);