Is there a way to take a screenshot using Java and save it to some sort of image?

后端 未结 8 717
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:19

Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then gra

相关标签:
8条回答
  • 2020-11-22 07:17

    If you'd like to capture all monitors, you can use the following code:

    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);
    
    0 讨论(0)
  • 2020-11-22 07:22

    You can use java.awt.Robot to achieve this task.

    below is the code of server, which saves the captured screenshot as image in your Directory.

    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketTimeoutException;
    import java.sql.SQLException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import javax.imageio.ImageIO;
    
    public class ServerApp extends Thread
    {
           private ServerSocket serverSocket=null;
           private static Socket server = null;
           private Date date = null;
           private static final String DIR_NAME = "screenshots";
    
       public ServerApp() throws IOException, ClassNotFoundException, Exception{
           serverSocket = new ServerSocket(61000);
           serverSocket.setSoTimeout(180000);
       }
    
    public void run()
       {
           while(true)
          {
               try
               {
                  server = serverSocket.accept();
                  date = new Date();
                      DateFormat dateFormat = new SimpleDateFormat("_yyMMdd_HHmmss");
                  String fileName = server.getInetAddress().getHostName().replace(".", "-");
                  System.out.println(fileName);
                  BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
                  ImageIO.write(img, "png", new File("D:\\screenshots\\"+fileName+dateFormat.format(date)+".png"));
                  System.out.println("Image received!!!!");
                  //lblimg.setIcon(img);
              }
             catch(SocketTimeoutException st)
             {
                   System.out.println("Socket timed out!"+st.toString());
     //createLogFile("[stocktimeoutexception]"+stExp.getMessage());
                      break;
                 }
                 catch(IOException e)
                 {
                      e.printStackTrace();
                      break;
             }
             catch(Exception ex)
            {
                  System.out.println(ex);
            }
          }
       }
    
       public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{
              ServerApp serverApp = new ServerApp();
              serverApp.createDirectory(DIR_NAME);
              Thread thread = new Thread(serverApp);
                thread.start();
       }
    
    private void createDirectory(String dirName) {
        File newDir = new File("D:\\"+dirName);
        if(!newDir.exists()){
            boolean isCreated = newDir.mkdir();
        }
     }
    } 
    

    And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.

    package com.viremp.client;
    
    import java.awt.AWTException;
    import java.awt.Dimension;
    import java.awt.Rectangle;
    import java.awt.Robot;
    import java.awt.Toolkit;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.Socket;
    import java.util.Random;
    
    import javax.imageio.ImageIO;
    
    public class ClientApp implements Runnable {
        private static long nextTime = 0;
        private static ClientApp clientApp = null;
        private String serverName = "192.168.100.18"; //loop back ip
        private int portNo = 61000;
        //private Socket serverSocket = null;
    
        /**
         * @param args
         * @throws InterruptedException 
         */
        public static void main(String[] args) throws InterruptedException {
            clientApp = new ClientApp();
            clientApp.getNextFreq();
            Thread thread = new Thread(clientApp);
            thread.start();
        }
    
        private void getNextFreq() {
            long currentTime = System.currentTimeMillis();
            Random random = new Random();
            long value = random.nextInt(180000); //1800000
            nextTime = currentTime + value;
            //return currentTime+value;
        }
    
        @Override
        public void run() {
            while(true){
                if(nextTime < System.currentTimeMillis()){
                    System.out.println(" get screen shot ");
                    try {
                        clientApp.sendScreen();
                        clientApp.getNextFreq();
                    } catch (AWTException e) {
                        // TODO Auto-generated catch block
                        System.out.println(" err"+e);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch(Exception e){
                        e.printStackTrace();
                    }
    
                }
                //System.out.println(" statrted ....");
            }
    
        }
    
        private void sendScreen()throws AWTException, IOException {
               Socket serverSocket = new Socket(serverName, portNo);
                 Toolkit toolkit = Toolkit.getDefaultToolkit();
                 Dimension dimensions = toolkit.getScreenSize();
                     Robot robot = new Robot();  // Robot class 
                     BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
                     ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
                     serverSocket.close();
        }
    }
    
    0 讨论(0)
提交回复
热议问题