Monday, February 21, 2011

Java multi-monitor screenshots

Random snippets I might want again one day ;)

Create a "C:\\CanDelete" directory before running any of this, or change the path building.

Take a screenshot of each monitor individually:
package com.blogspot.whileonefork.screencapture;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;


public class EachMonitor {
 public static void main(String[] argv) throws Exception {
  //Take a screenshot of every monitor
  GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice[] screens = ge.getScreenDevices();
  
  for (GraphicsDevice screen : screens) {
   Robot robotForScreen = new Robot(screen);
   Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
   
   //The screen bounds have an annoying tendency to have an offset x/y; we want (0,0) => (width, height)
   screenBounds.x = 0;
   screenBounds.y = 0;
   BufferedImage screenShot = robotForScreen.createScreenCapture(screenBounds);
   String ext = "jpg";
   String outputFile = "C:\\CanDelete\\screenshot_" 
    + screen.getIDstring().replaceAll("[^A-Za-z0-9]", "_")
    + "."
    + ext;   
   ImageIO.write(screenShot, ext, new File(outputFile));
   System.out.println("Saved " + outputFile 
    + " of " + screen.getIDstring() 
    + " xy=(" + screenBounds.x + "," + screenBounds.y + ")"
    + " bounds=("+ screenBounds.width + "," + screenBounds.height + ")");
  }
 }
}


Take a single big screenshot of all monitors:

package com.blogspot.whileonefork.screencapture;

import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class AllMonitors {
 public static void main(String[] argv) throws Exception {      
  /**
   * Take one big screenshot of the entire UI. 
   * On my Windows box monitors seem to act like they are side by side on X, extending on Y.
   * Seems, at least on windows, to ignore any offset config setup in display properties.
   */
  GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice[] screens = ge.getScreenDevices();
  
  Rectangle allScreenBounds = new Rectangle();
  for (GraphicsDevice screen : screens) {
   Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
   
   allScreenBounds.width += screenBounds.width;
   allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);      
  }
  
  Robot robot = new Robot();
  BufferedImage screenShot = robot.createScreenCapture(allScreenBounds);
  
  String ext = "jpg";
  String outputFile = "C:\\CanDelete\\AllMonitors" 
   + "."
   + ext;   
  ImageIO.write(screenShot, ext, new File(outputFile));
  System.out.println("Saved " + outputFile 
   + " of all monitors " 
   + " xy=(" + allScreenBounds.x + "," + allScreenBounds.y + ")"
   + " bounds=("+ allScreenBounds.width + "," + allScreenBounds.height + ")");  
 } 
}


All this has been tested exactly once on a Windows box with two monitors of substantially different size; ymmv :)

57 comments:

Dustin said...

This seems to give errors when the first monitor is lower than the following monitors. If anyone else runs into this problem a corrected version can be found below. Also note that this version does not save a file, and instead returns a buffered image.


package book;

import java.awt.AWTException;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AllMonitors {

public BufferedImage getScreenshot() {

//get handle to graphics environment
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();

//if screens are detected proceed
if (screens.length > 0) {

try {
//get the first screen
GraphicsDevice a = screens[0];

//get the monitor resolution
Toolkit t = Toolkit.getDefaultToolkit();
Rectangle allScreenBounds = new Rectangle(t.getScreenSize());

//offset screen capture (in cases where first monitor is not the
//highest this will come into effect)
allScreenBounds.y = -1 * screens[0].getDefaultConfiguration().getBounds().y;

//take screenshot
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(allScreenBounds);

return screenShot;
} catch (AWTException ex) {
Logger.getLogger(AllMonitors.class.getName()).log(Level.SEVERE, null, ex);
}
}

//if no screens detected return null
return null;
}
}

Unknown said...

The code to compute the virtual screen bounds can be found in the jdk's javadoc (http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/GraphicsConfiguration.html):

Rectangle virtualBounds = new Rectangle();
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsDevice[] gs =
ge.getScreenDevices();
for (int j = 0; j < gs.length; j++) {
GraphicsDevice gd = gs[j];
GraphicsConfiguration[] gc =
gd.getConfigurations();
for (int i=0; i < gc.length; i++) {
virtualBounds =
virtualBounds.union(gc[i].getBounds());
}
}

Scott Schafer said...

Thanks for this post, but especially +1000 to Dustin. If I had hair, I would have pulled it all out over this bug. Your comment saved me a lot of aggravation.

Unknown said...

add this to the end of the for loop and it will work with as many monitors as you have ::: allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);

Unknown said...

add this to the end of the for loop and it will work with as many monitors as you have ::: allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);

Asim Shaikh said...

Thanks for sharing the info, keep up the good work going.... I really enjoyed exploring your site. good resource...best modem router combo

priya said...

I appreciate that you produced this wonderful article to help us get more knowledge about this topic. I know, it is not an easy task to write such a big article in one day, I've tried that and I've failed. But, here you are, trying the big task and finishing it off and getting good comments and ratings. That is one hell of a job done!

Data Science course in Chennai
Data science course in bangalore
Data science course in pune
Data science online course
Data Science Interview questions and answers
Data Science Tutorial

rohini said...

Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
Best Devops Training in pune
Devops Training in Bangalore
Microsoft azure training in Bangalore
Power bi training in Chennai

sheikhali said...

nice one...!
t shirt printing in perth

Deepak said...

Amazon Quiz Answers Today
Deals Ki Dunia

svrtechnologies said...

Thanks for Sharing Such an useful & Informative Stuff...

data science tutorial

digitaltucr said...


I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing.
data analytics courses
ExcelR Data Science training in Mumbai
data science interview questions
ExcelR Business Analytics courses in Mumbai

Ecare Technologies said...

I have read your blog its very attractive and impressive. I like it your blog...
Data Science Training in Bangalore
Data Science Courses in Bangalore

Unknown said...

Thanks for sharing the info, keep up the good work going....You may have to try get clash of magic apk

j8899 said...


Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.

digital marketing courses mumbai

BestTrainingKolkata said...

This article contains some of the most informative content I've read in quite some time. The points of this content are clear-cut and engaging. I think much like this writer.
SAP training in Kolkata
Best SAP training in Kolkata
SAP training institute in Kolkata

Avijit said...

There are numerous parts of this article on which I agree with you. You have created neural connections in my mind not utilized frequently. Much thanks to you for getting my neurons bouncing.


Denial management software
Denials management software
Hospital denial management software
Self Pay Medicaid Insurance Discovery
Uninsured Medicaid Insurance Discovery
Medical billing Denial Management Software
Self Pay to Medicaid
Charity Care Software
Patient Payment Estimator
Underpayment Analyzer
Claim Status

nisharoshan said...

Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.

Web Designing Training Course in Chennai | Certification | Online Course Training | Web Designing Training Course in Bangalore | Certification | Online Course Training | Web Designing Training Course in Hyderabad | Certification | Online Course Training | Web Designing Training Course in Coimbatore | Certification | Online Course Training | Web Designing Training Course in Online | Certification | Online Course Training





devi said...

Excellent blog with lots of information, keep sharing. I am waiting for your more posts like this or related to any other informative topic.
Data Science Training In Chennai | Certification | Data Science Courses in Chennai | Data Science Training In Bangalore | Certification | Data Science Courses in Bangalore | Data Science Training In Hyderabad | Certification | Data Science Courses in hyderabad | Data Science Training In Coimbatore | Certification | Data Science Courses in Coimbatore | Data Science Training | Certification | Data Science Online Training Course

Anonymous said...

Thank you for this informative blog
python training in bangalore | python online training
artificial intelligence training in bangalore | artificial intelligence online training
machine learning training in bangalore | machine learning online training
blockchain training in bangalore | blockchain online training
uipath training in bangalore | uipath online training

Anonymous said...

Much obliged for this post, yet particularly +1000 to Dustin. In the event that I had hair, I would have hauled everything out over this bug. Your remark spared me a great deal of disturbance....
rooftop snipers

Insta Follower said...

Having read this I believed it was really informative. I appreciate you taking the time and effort to put this informative article together. I once again find myself spending a lot of time both reading and posting comments. But so what, it was still worth it!

Buy Instagram Likes $1

Maneesha said...

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well..
data scientist training and placement in hyderabad

sheikhali said...

Thank you for sharing this information; keep up the good work.... I had a great time looking at your website. a useful resource..
VAPOR VM

sheikhali said...

This is an excellent tutorial. Thank you for sharing such useful information. It's quite beneficial. This site is very useful for those who want to learn. Continue to share updated tutorials.....
linkedin vaporvm

Bhuvana said...

Thank you quite much for discussing this type of helpful informative article. Will certainly stored and reevaluate your Website.

AWS Training in Hyderabad

digital marketing course Mumbai said...

Wow. That is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious. Thanks for Sharing This Article. It is very so much valuable content. Digital marketing training

digital marketing course Mumbai said...

Very nice blogs!!! i have to learning for lot of information for this sites…Sharing for wonderful information. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing Digital marketing

digital marketing course Mumbai said...

very well explained. I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. Keep it up. Digital marketing training Mumbai

digital marketing course Mumbai said...

Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging. digital marketing course Mumbai

traininginstitute said...

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work
full stack web development course in malaysia

PMP Training in Malaysia said...

360DigiTMG, the top-rated organisation among the most prestigious industries around the world, is an educational destination for those looking to pursue their dreams around the globe. The company is changing careers of many people through constant improvement, 360DigiTMG provides an outstanding learning experience and distinguishes itself from the pack. 360DigiTMG is a prominent global presence by offering world-class training. Its main office is in India and subsidiaries across Malaysia, USA, East Asia, Australia, Uk, Netherlands, and the Middle East.

360digiTMG.com said...

I really loved reading your blog. It was very well authored and easy to understand. Unlike other blogs I have read which are really not that good.Thanks alot! data science training in mysore

360digiTMG.com said...

I have read your article; it is very informative and helpful for me. I admire the valuable information you offer in your articles. Thanks for posting it. data science course in surat

eMexo Technologies said...

It become an attractive part of a blog when author uses indirect speech while writing a blog. It shows your creative mind as well as make your written essay different from others.
devops training in bangalore
devops course in bangalore
aws training in bangalore

Divya Sharma said...

The author provides clear and concise Java code snippets for capturing screenshots of multiple monitors. These snippets are well-documented and helpful for anyone working on similar tasks.
Is iim skills fake?

Data Analytics Courses in Agra said...

The author offers succinct and understandable Java code samples for taking screenshots on several monitors. For anyone working on related jobs, these snippets are beneficial and well-documented.
Data Analytics Courses in Agra

Aishwarya said...

"An insightful read!
Digital Marketing Courses in Hamburg

Manish Roy said...

This is a wonderfully intriguing post. I've been seeking this type of information and found it enjoyable to read. Please continue to publish. Thanks for sharing.
daa Analytics courses in leeds

Manish Roy said...

Great piece! I appreciate you sharing this valuable information. Please continue to do so.
Great piece! I appreciate you sharing this valuable information. Please continue to do so.

DMC in Italy said...

The blog post provides valuable insights and collection of Java snippets for capturing screenshots across multiple monitors. thanks for sharing valuable blog.
Digital Marketing Courses in Italy

How Digital marketing is changing business said...

Great code snippets! Your detailed comments make it easy to understand and implement. Thanks for sharing this useful Java multi-monitor screenshot solution.

How Digital marketing is changing business

Aishwarya said...

The blog post provides great tutorial on Java multi-monitor screenshots.
Investment banking training Programs

Rajsingh said...

Java's class allows developers to programmatically capture screen content, providing flexibility for applications that operate on multiple monitors. This feature proves beneficial in scenarios where precise monitoring, visual validation, or documentation of multi-monitor setups is essential. nice article.
Data analytics framework

Gogou Misao said...

Wonderful idea and some really useful code as well. Thanks for sharing.
Investment banking analyst jobs

Digital said...

Great article on capturing screenshots across multiple monitors in Java! This can be a tricky task, and I appreciate how you broke down the process for handling different screen configurations. The code examples are especially helpful for understanding how to capture and stitch together screenshots from different monitors. It would be interesting to see some tips on optimizing performance when working with high-resolution displays or how to handle various screen aspect ratios. Thanks for sharing this valuable resource!

Digital Marketing Course In Hyderabad

Rachana said...

Fantastic guide on capturing multi-monitor screenshots in Java! Your clear instructions and practical tips will surely help many developers streamline their workflow. Keep sharing your expertise; it’s inspiring to see how you tackle such niche topics!
Data Science Courses in Singapore

IIMSkillsAnubhutiv said...

thanks for sharing good technical content on Java
helpful for real time coders
data analytics courses in Singapore

Gouse said...

"Great article! I love how you explained the process of taking multi-monitor screenshots in Java. The tips and code snippets are really helpful for anyone looking to implement this feature. Thanks for sharing!"

Digital Marketing Course In Hyderabad

Sadhvi said...

This is a fantastic resource for anyone looking to capture screenshots across multiple monitors using Java! I love how you’ve provided both individual and combined screenshot methods, which offers flexibility depending on user needs. Data science courses in Mysore

Data science Courses in Norwich said...

I have gone through your blog. It was really informative and helpful for monitoring the screenshot.
Thank you for sharing.
Data science Courses in Germany

Sakshi Gupta said...

"Java multi-monitor screenshot functionality is useful for capturing the entire workspace across multiple screens. It can enhance the way you monitor and manage applications in a multi-display setup."

Data Science Course in Chennai

RICHA said...

This blog provides a useful guide on capturing screenshots across multiple monitors in Java. A great resource for developers working with multi-monitor setups and screenshot automation!
Data science course in Gurgaon

P. Zaheer Khan said...

Great post! I’ve always struggled with capturing screenshots across multiple monitors in Java, but your explanation makes it so much clearer.keep sharing and brings unique content. thank you
Data science course in Bangalore

Sunaina kaur said...

Wow, this post is fantastic! It’s so hard to find a straightforward way to capture screenshots across multiple monitors in Java. This solution is simple yet effective. Definitely bookmarking this for future reference. Thanks for the helpful tips!
Data science courses in chennai

AI Readers club said...

Great post! The method you’ve shared for taking screenshots across multiple monitors in Java is really useful. It’s a great technique for developers working with multi-screen setups. Thanks for sharing this practical solution, and I look forward to more posts like this!

Data science courses in Bangladesh

NB said...

The step-by-step approach really helped me understand the topic better. Thanks for sharing!
GST Course

Post a Comment