Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get screenshot of any Linux/Windows application running outside of the JVM

Is it possible to use Java to get a screenshot of an application external to Java, say VLC/Windows Media Player, store it as an Image object and then display it in a JLabel or something of a similar nature? Does anybody know if this is possible and if so does anybody have a general idea as to how to do it?

Note: I just need to find out how to get a screenshot and store it as some form of Image object. After that I can use, manipulate it, display it, etc.

like image 952
Dillon Chaffey Avatar asked Dec 25 '11 11:12

Dillon Chaffey


2 Answers

Here is the answer for Windows (not sure if alt+printScr works on linux :P)

I guess one way to achieve this

1. using Robot class to fire alt+printScreen Command (this captures active window to clipboard)

2. read the clipboard!

Here are the two pieces of code that do that. I have not actually tried, but something that I pieced together.

Code to Fire commands to get active window on clipboard

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class ActiveWindowScreenShot
{
 /**
  * Main method
  * 
  * @param args (not used)
  */
 public static void main(String[] args)
 {
  Robot robot;

  try {
   robot = new Robot();
  } catch (AWTException e) {
   throw new IllegalArgumentException("No robot");
  }

  // Press Alt + PrintScreen
  // (Windows shortcut to take a screen shot of the active window)
  robot.keyPress(KeyEvent.VK_ALT);
  robot.keyPress(KeyEvent.VK_PRINTSCREEN);
  robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
  robot.keyRelease(KeyEvent.VK_ALT);

  System.out.println("Image copied.");
 }
}

Code to read image on clipboard

// If an image is on the system clipboard, this method returns it;
// otherwise it returns null.
public static Image getClipboard() {
    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

    try {
        if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
            Image text = (Image)t.getTransferData(DataFlavor.imageFlavor);
            return text;
        }
    } catch (UnsupportedFlavorException e) {
    } catch (IOException e) {
    }
    return null;
}

You can manage the control as you need to! Let me know if this works for you. but this is certainly on my todo to try it out!

like image 176
Shaunak Avatar answered Oct 13 '22 08:10

Shaunak


You can get screen shot of whole screen using class named Robot. Unfortunately you cannot get location and size of windows that belong to other applications using pure java solution. To do this you need other tools (scripting, JNI, JNA). These tools are not cross-platform.

like image 30
AlexR Avatar answered Oct 13 '22 09:10

AlexR