/**
   * @param bound The bounds of the screen
   * @throws IllegalArgumentException - if width and height < 0
   * @throws SecurityException - if readDisplayPixels permission is not granted
   * @throws HeadlessException - if GraphicsEnvironment.isHeadless() returns true.
   */
  public void capture(Rectangle bound) {
    if (bound == null || bound.width == 0 || bound.height == 0) {
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      image = robot.createScreenCapture(new Rectangle(d));
      return;
    }

    image = robot.createScreenCapture(bound);
  }
 /**
  * 抓屏方法
  *
  * @see 该方法抓的是全屏,并且当传入的fileName参数为空时会将抓屏图片默认保存到用户桌面上
  * @param fileName 抓屏后的图片保存名称(含保存路径及后缀),传空时会把图片自动保存到桌面
  * @param isAutoOpenImage 是否自动打开图片
  * @return 抓屏成功返回true,反之false
  */
 public static boolean captureScreen(String fileName, boolean isAutoOpenImage) {
   if (isEmpty(fileName)) {
     String desktop = FileSystemView.getFileSystemView().getHomeDirectory().getPath();
     String separator = System.getProperty("file.separator");
     String imageName = "截屏_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".png";
     fileName = desktop + separator + imageName;
   }
   String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
   File file = new File(fileName);
   // 获取屏幕大小
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle = new Rectangle(screenSize);
   try {
     Robot robot = new Robot();
     BufferedImage image = robot.createScreenCapture(screenRectangle);
     ImageIO.write(image, fileSuffix, file);
     // 自动打开图片
     if (isAutoOpenImage) {
       if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
         Desktop.getDesktop().open(file);
       }
     }
   } catch (AWTException e) {
     return false;
   } catch (IOException e) {
     return false;
   }
   return true;
 }
Beispiel #3
0
  /**
   * Runs a sample test procedure
   *
   * @param robot the robot attached to the screen device
   */
  public static void runTest(Robot robot) {
    // simulate a space bar press
    robot.keyPress(' ');
    robot.keyRelease(' ');

    // simulate a tab key followed by a space
    robot.delay(2000);
    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);
    robot.keyPress(' ');
    robot.keyRelease(' ');

    // simulate a mouse click over the rightmost button
    robot.delay(2000);
    robot.mouseMove(200, 50);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);

    // capture the screen and show the resulting image
    robot.delay(2000);
    BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, 400, 300));

    ImageFrame frame = new ImageFrame(image);
    frame.setVisible(true);
  }
  private void createShadowBorder() {
    backgroundImage =
        new BufferedImage(
            getWidth() + SHADOW_WIDTH, getHeight() + SHADOW_WIDTH, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D) backgroundImage.getGraphics();

    try {
      Robot robot = new Robot(getGraphicsConfiguration().getDevice());
      BufferedImage capture =
          robot.createScreenCapture(
              new Rectangle(getX(), getY(), getWidth() + SHADOW_WIDTH, getHeight() + SHADOW_WIDTH));
      g2.drawImage(capture, null, 0, 0);
    } catch (AWTException e) {
      e.printStackTrace();
    }

    BufferedImage shadow =
        new BufferedImage(
            getWidth() + SHADOW_WIDTH, getHeight() + SHADOW_WIDTH, BufferedImage.TYPE_INT_ARGB);
    Graphics graphics = shadow.getGraphics();
    graphics.setColor(new Color(0.0f, 0.0f, 0.0f, 0.3f));
    graphics.fillRoundRect(6, 6, getWidth(), getHeight(), 12, 12);

    g2.drawImage(shadow, getBlurOp(7), 0, 0);
  }
Beispiel #5
0
  public static void main(String[] argv) throws AWTException {
    final JFrame f = new JFrame("Robot Test");
    final JButton b = new JButton("Click me");
    final JTextField tf = new JTextField();
    final RobotTest t = new RobotTest();
    f.add(tf, BorderLayout.NORTH);
    f.add(t, BorderLayout.CENTER);
    f.add(b, BorderLayout.SOUTH);
    f.pack();
    f.setLocation(0, 0);
    f.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            f.dispose();
          }
        });
    f.setVisible(true);

    final Robot r = new Robot();
    r.setAutoDelay(50);
    r.delay(1000);
    image = r.createScreenCapture(new Rectangle(0, 0, 200, 200));
    t.repaint();
    //        for(int i = 0; i < 400; i++){
    //            r.mouseMove(i, i);
    //        }

    b.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            tf.setText("Clicked !");
          }
        });

    moveToCenterOfComponent(r, b);
    r.mousePress(InputEvent.BUTTON1_MASK);
    r.mouseRelease(InputEvent.BUTTON1_MASK);

    Point p = f.getLocationOnScreen();
    p.translate(f.getWidth() / 2, 5);
    r.mouseMove((int) p.getX(), (int) p.getY());
    r.mousePress(InputEvent.BUTTON1_MASK);
    for (int i = 0; i < 100; i++) {
      r.mouseMove((int) p.getX() + i, (int) p.getY() + i);
    }
    r.mouseRelease(InputEvent.BUTTON1_MASK);
    t.addMouseMotionListener(
        new MouseMotionAdapter() {
          public void mouseMoved(MouseEvent event) {
            Point p = event.getPoint();
            SwingUtilities.convertPointToScreen(p, t);
            crtColor = r.getPixelColor(p.x, p.y);
            // Graphics g = t.getGraphics();
            // g.setColor(crtColor);
            // g.fillRect(25,225, 50,50);
            t.repaint();
          }
        });
  }
Beispiel #6
0
  public static void captureScreen(Component Area) {

    // Find out where the user would like to save their screen shot
    String fileName = null;
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Screen Shots", "png");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showSaveDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File saveFile = new File(chooser.getSelectedFile().getPath() + ".png");
      fileName = saveFile.toString();

      // Check to see if we will overwrite the file
      if (saveFile.exists()) {
        int overwrite =
            JOptionPane.showConfirmDialog(null, "File already exists, do you want to overwrite?");
        if (overwrite == JOptionPane.CANCEL_OPTION
            || overwrite == JOptionPane.CLOSED_OPTION
            || overwrite == JOptionPane.NO_OPTION) {
          return;
        }
      }
    }
    // If they didn't hit approve, return
    else {
      return;
    }

    // Determine the exact coordinates of the screen that is to be captured
    Dimension screenSize = Area.getSize();
    Rectangle screenRectangle = new Rectangle();
    screenRectangle.height = screenSize.height;
    screenRectangle.width = screenSize.width;
    screenRectangle.x = Area.getLocationOnScreen().x;
    screenRectangle.y = Area.getLocationOnScreen().y;

    // Here we have to make the GUI Thread sleep for 1/4 of a second
    // just to give the save dialog enough time to close off of the
    // screen. On slower computers they were capturing the screen
    // before the dialog was out of the way.
    try {
      Thread.currentThread();
      Thread.sleep(250);
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    }

    // Attempt to capture the screen at the defined location.
    try {
      Robot robot = new Robot();
      BufferedImage image = robot.createScreenCapture(screenRectangle);
      ImageIO.write(image, "png", new File(fileName));
    } catch (AWTException e) {
      e.printStackTrace();
    } catch (IOException e) {
      JOptionPane.showMessageDialog(null, "Could not save screen shoot at: " + fileName);
      e.printStackTrace();
    }
  }
Beispiel #7
0
 /**
  * Boom! Head shot!
  *
  * @return the screen shot
  */
 private static Image screenShot(Dimension ss) {
   try {
     if (robot == null) robot = new Robot();
     return robot.createScreenCapture(new Rectangle(0, 0, ss.width, ss.height));
   } catch (Exception e) {
     return null;
   }
 }
Beispiel #8
0
 /**
  * Creates a ScreenShot of the client's desktop of the area provided.
  *
  * @param x1 The x value of the top left point.
  * @param y1 The y value of the top left point.
  * @param x2 The x value of the bottom right point.
  * @param y2 The y value of the bottom right point.
  * @return The image.
  */
 public static BufferedImage captureDesktop(int x1, int y1, int x2, int y2) {
   try {
     final Robot robot = new Robot();
     return robot.createScreenCapture(new Rectangle(x1, y1, x2, y2));
   } catch (AWTException ignored) {
     return null;
   }
 }
 public void screenshot(String fileName) throws Exception {
   Robot robot = new Robot();
   Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle rect = new Rectangle(0, 0, d.width, d.height);
   BufferedImage image = robot.createScreenCapture(rect);
   file_path = fileName + "pic";
   ImageIO.write(image, "jpg", new File(file_path));
 }
Beispiel #10
0
 /**
  * Creates a ScreenShot of the client's entire desktop.
  *
  * @return The image to return.
  */
 public static BufferedImage captureDesktop() {
   try {
     final Robot robot = new Robot();
     final Dimension d = getScreenDimensions();
     final Rectangle r = new Rectangle(0, 0, d.width, d.height);
     return robot.createScreenCapture(r);
   } catch (AWTException ignored) {
     return null;
   }
 }
  private void refresh(boolean needStable) {
    boolean looking = true;
    Date start = new Date();

    while (true) {
      boolean stable = true;
      looking = !looking;

      int numWhite = 0;
      int numBlack = 0;

      int[] cnt = new int[Gem.getIdxCnt()];

      BufferedImage scr =
          robot.createScreenCapture(
              new Rectangle(SCAN_LEFT, SCAN_TOP, 8 * SCAN_BLOCK, 8 * SCAN_BLOCK));

      getGraphics().drawImage(scr, 0, 120, 8 * SCAN_BLOCK, 8 * SCAN_BLOCK, null);

      for (int x = 0; x < 8; x++) {
        for (int y = 0; y < 8; y++) {
          Position p = grid[x][y];
          Gem g = null;
          if (!looking) {
            g = p.dontLook(scr);
          } else {
            g = p.look(scr);
          }
          if (g == Gem.WHITE) numWhite++;
          else if (g == Gem.UNKNOWN) numBlack++;
          cnt[g.getIdx()]++;
        }
      }
      stats = cnt;
      if (looking) {
        if (numWhite > 20) {
          // not on real board! freeze!
        } else {
          if (numBlack > 5) stable = false;

          if (stable) return;

          if (!stable && new Date().getTime() - start.getTime() > 300) return;
        }
      }
      //			try
      //			{
      //				Thread.sleep(100);
      //			}
      //			catch (InterruptedException e)
      //			{
      //			}
    }
  }
 public void updateBackground() {
   try {
     Robot rbt = new Robot();
     Toolkit tk = Toolkit.getDefaultToolkit();
     Dimension dim = tk.getScreenSize();
     background =
         rbt.createScreenCapture(new Rectangle(0, 0, (int) dim.getWidth(), (int) dim.getHeight()));
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Beispiel #13
0
  // ekran görüntüsü al.
  public static BufferedImage screenShotGetir() throws AWTException {
    /*
     * http://www.arulraj.net/2010/06/print-screen-using-java.html
     */

    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension dim = tk.getScreenSize();
    Rectangle rect = new Rectangle(dim);
    Robot myRobot = new Robot();

    BufferedImage myBufferedImage = myRobot.createScreenCapture(rect);
    return myBufferedImage;
  }
Beispiel #14
0
 public TransparentWindow(BufferedImage img, int x, int y) {
   image = img;
   try {
     Robot robot = new Robot();
     Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
     screen = robot.createScreenCapture(new Rectangle(0, 0, d.width, d.height));
   } catch (AWTException e) {
     throw new Error(e);
   }
   setBounds(x, y, img.getWidth(), img.getHeight());
   setVisible(true);
   buffer = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
   graphics = (Graphics2D) buffer.getGraphics();
 }
Beispiel #15
0
 @Override
 public void run() {
   try {
     corriendo = true;
     out = new ByteArrayOutputStream();
     robot = new Robot();
     lastBufferedImage = null;
   } catch (AWTException ex) {
     Logger.getLogger(GeneradorPantalla.class.getName()).log(Level.SEVERE, null, ex);
   }
   screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
   while (corriendo) {
     try {
       Thread.sleep(400);
       // Preparo el evento
       TipoEventosGUI elEvento;
       // Capturo pantalla
       tmpImage = robot.createScreenCapture(screenRect);
       // Si la imagen no es nula, hay alguien conectado y es una nueva imagen
       if (tmpImage != null && manejador.enviarPantalla() && newImage(tmpImage)) {
         // Esta es la nueva última imagen.
         lastBufferedImage = tmpImage;
         // Convierto la imagen a un Array de Bytes.
         ImageIO.write(tmpImage, "JPEG", out);
         // Creo un arreglo de parámetros para el evento
         ArrayList<Object> losParams = new ArrayList<Object>();
         // Le agrego la imagen convertida a bytes
         losParams.add(out);
         // Creo el evento
         elEvento = new TipoEventosGUI(TipoEventosGUI.imagenPantalla, losParams);
         // Y finalmente envío la pantalla al manejador de conexiones
         // para que la envíe a los alumnos que esperan recibirla.
         manejador.enviarPantalla(elEvento);
         out.flush();
       }
     } catch (IOException ex) {
       Logger.getLogger(GeneradorPantalla.class.getName()).log(Level.SEVERE, null, ex);
       // corriendo = false;
     } catch (InterruptedException ex) {
       try {
         // Logger.getLogger(GeneradorPantalla.class.getName()).log(Level.SEVERE, null, ex);
         out.close();
       } catch (IOException ex1) {
         Logger.getLogger(GeneradorPantalla.class.getName()).log(Level.SEVERE, null, ex1);
       }
       corriendo = false;
     }
   }
 }
  /**
   * Takes a screenshot and saves the image to disk. This method will attempt to encode the image
   * according to the file extension of the given output file. If this is not possible (because the
   * encoding type is not supported), then the default encoding type will be used. If the default
   * encoding type is used, an appropriate extension will be added to the filename.
   *
   * @param captureRect Rect to capture in screen coordinates.
   * @param scaleFactor Degree to which the image should be scaled, in percent. A <code>scaleFactor
   *     </code> of <code>100</code> produces an unscaled image. This value must be greater than
   *     <code>0</code> and less than or equal to <code>200</code>.
   * @param outputFile Path and filename for the created image.
   */
  public void takeScreenshot(Rectangle captureRect, double scaleFactor, File outputFile) {
    // Create screenshot
    java.awt.Robot robot;
    File out = outputFile;

    try {
      robot = new java.awt.Robot();
      BufferedImage image = robot.createScreenCapture(captureRect);

      int scaledWidth = (int) Math.floor(image.getWidth() * scaleFactor);
      int scaledHeight = (int) Math.floor(image.getHeight() * scaleFactor);
      BufferedImage imageOut =
          new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
      // Scale it to the new size on-the-fly
      Graphics2D graphics2D = imageOut.createGraphics();
      graphics2D.setRenderingHint(
          RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
      graphics2D.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);

      // Save captured image using given format, if supported.
      String extension = getExtension(out.getName());
      if (extension.length() == 0
          || !ImageIO.getImageWritersBySuffix(extension).hasNext()
          || !ImageIO.write(imageOut, extension, out)) {

        // Otherwise, save using default format
        out = new File(outputFile.getPath() + EXTENSION_SEPARATOR + DEFAULT_IMAGE_FORMAT);
        if (!ImageIO.write(imageOut, DEFAULT_IMAGE_FORMAT, out)) {

          // This should never happen, so log as error if it does.
          // In this situation, the screenshot will not be saved, but
          // the test step will still be marked as successful.
          log.error(
              "Screenshot could not be saved. "
                  + //$NON-NLS-1$
                  "Default image format ("
                  + DEFAULT_IMAGE_FORMAT //$NON-NLS-1$
                  + ") is not supported."); //$NON-NLS-1$
        }
      }

    } catch (AWTException e) {
      throw new RobotException(e);
    } catch (IOException e) {
      throw new StepExecutionException(
          "Screenshot could not be saved", //$NON-NLS-1$
          EventFactory.createActionError(TestErrorEvent.FILE_IO_ERROR));
    }
  }
  public static void captureScreen(String fileName) throws Exception {
    File file = new File(fileName);

    file.mkdirs();

    Robot robot = new Robot();

    Toolkit toolkit = Toolkit.getDefaultToolkit();

    Rectangle rectangle = new Rectangle(toolkit.getScreenSize());

    BufferedImage bufferedImage = robot.createScreenCapture(rectangle);

    ImageIO.write(bufferedImage, "jpg", file);
  }
Beispiel #18
0
 static void move(Robot r, Player p) throws Exception {
   Board b = BoardReader.read(r);
   final Piece next =
       NextPiece.readNextPiece(r.createScreenCapture(new Rectangle(NPX, NPY, 256, 256)));
   List<Pair<Move, Board>> moves = PiecePlacements.moves(b);
   if (moves == null) return;
   Collections.sort(
       moves,
       new Comparator<Pair<Move, Board>>() {
         public int compare(Pair<Move, Board> a, Pair<Move, Board> b) {
           return MoveEvaluator.score(b.second, next) - MoveEvaluator.score(a.second, next);
         }
       });
   p.play(moves.get(0).first);
 }
  /** Do screen capture and save it as image */
  private static void captureScreenAndSave() {

    try {
      Robot robot = new Robot();
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
      System.out.println("About to screen capture - " + rectangle);
      java.awt.image.BufferedImage image = robot.createScreenCapture(rectangle);
      javax.imageio.ImageIO.write(image, "jpg", new java.io.File("ScreenImage.jpg"));
      robot.delay(3000);
    } catch (Throwable t) {
      System.out.println("WARNING: Exception thrown while screen capture!");
      t.printStackTrace();
    }
  }
  /**
   * Capture a part of the desktop screen using <tt>java.awt.Robot</tt>.
   *
   * @param x x position to start capture
   * @param y y position to start capture
   * @param width capture width
   * @param height capture height
   * @return <tt>BufferedImage</tt> of a part of the desktop screen or null if Robot problem
   */
  public BufferedImage captureScreen(int x, int y, int width, int height) {
    BufferedImage img = null;
    Rectangle rect = null;

    if (robot == null) {
      /* Robot has not been created so abort */
      return null;
    }

    if (logger.isInfoEnabled()) logger.info("Begin capture: " + System.nanoTime());
    rect = new Rectangle(x, y, width, height);
    img = robot.createScreenCapture(rect);
    if (logger.isInfoEnabled()) logger.info("End capture: " + System.nanoTime());

    return img;
  }
  public String captureAndEncodeSystemScreenshot()
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    final ByteArrayOutputStream outStream;
    final BufferedImage bufferedImage;
    final Rectangle captureSize;
    final byte[] encodedData;
    final Robot robot;

    robot = RobotRetriever.getRobot();
    captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    bufferedImage = robot.createScreenCapture(captureSize);
    outStream = new ByteArrayOutputStream();
    ImageIO.write(bufferedImage, "png", outStream);

    encodedData = Base64.encodeBase64(outStream.toByteArray());

    return new String(encodedData);
  }
Beispiel #22
0
  public static void main(String[] args) {
    try {
      Random ran = new Random();
      int num = ran.nextInt();
      Robot robot = new Robot();
      String format = "jpg";
      String fileName = "FullScreenshot" + num + "." + format;

      Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
      BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
      ImageIO.write(screenFullImage, format, new File(fileName));
      Process p =
          new ProcessBuilder("explorer.exe", "/select,C:\\screenshots\\" + fileName).start();

    } catch (AWTException e) {
      System.err.println(e.getMessage());
    } catch (IOException ex) {
      System.err.println(ex.getMessage());
    }
  }
Beispiel #23
0
  public void screenshot() {

    if (System.currentTimeMillis() - ultimaFoto > 1000) {

      try {
        Robot robot = new Robot();
        Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        BufferedImage bufferedImage = robot.createScreenCapture(captureSize);

        File outputfile =
            new File(
                System.getProperty("user.home") + "\\Desktop\\ScreenShot" + ultimaFoto + ".jpg");
        ImageIO.write(bufferedImage, "jpg", outputfile);
      } catch (IOException e) {

      } catch (AWTException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      ultimaFoto = System.currentTimeMillis();
    }
  }
Beispiel #24
0
  @Override
  public void run() {
    try {
      System.out.println("Caught U!!...");
      Robot robot = new Robot();
      Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
      int width = (int) d.getWidth();
      int height = (int) d.getHeight();

      Image image = robot.createScreenCapture(new Rectangle(0, 0, width, height));

      BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      Graphics g = bi.createGraphics();
      g.drawImage(image, 0, 0, width, height, null);

      String fileNameToSaveTo = "C:/temp/screenCapture_" + createTimeStampStr() + ".PNG";
      writeImage(bi, fileNameToSaveTo, "PNG");

      System.out.println("Screen Captured Successfully and Saved to:\n" + fileNameToSaveTo);
    } catch (Exception er) {
      System.out.println("Error: " + er);
    }
  }
Beispiel #25
0
 public void screeny() {
   try {
     Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
     Point point = window.getLocationOnScreen();
     int x = (int) point.getX();
     int y = (int) point.getY();
     int w = window.getWidth();
     int h = window.getHeight();
     Robot robot = new Robot(window.getGraphicsConfiguration().getDevice());
     Rectangle captureSize = new Rectangle(x, y, w, h);
     java.awt.image.BufferedImage bufferedimage = robot.createScreenCapture(captureSize);
     String fileExtension = "Elysium";
     for (int i = 1; i <= 1000; i++) {
       File file = new File("Screenshots/" + fileExtension + " " + i + ".png");
       if (!file.exists()) {
         screenshot = i;
         takeScreeny = true;
         break;
       }
     }
     File file =
         new File(
             (new StringBuilder())
                 .append("Screenshots/" + fileExtension + " ")
                 .append(screenshot)
                 .append(".png")
                 .toString());
     if (takeScreeny == true) {
       // client.pushMessage("A picture has been saved in your screenshots folder.", 0, "");
       ImageIO.write(bufferedimage, "png", file);
     } else {
       // client.pushMessage("@red@Uh oh! Your screeny folder is full!", 0, "");
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 public BufferedImage createScreenCapture(Rectangle screenRect) {
   return robot.createScreenCapture(screenRect);
 }
Beispiel #27
0
 // returns true if new image is actually different from previous
 private BufferedImage captureNewImage() {
   refreshInfo();
   return robot.createScreenCapture(new Rectangle(getX(), getY(), getWidth(), getHeight()));
 }
Beispiel #28
0
 /**
  * Updates the background. Makes a new screen capture at the given coordiantes.
  *
  * @param x The x coordinate.
  * @param y The y coordinate.
  */
 public void updateBackground(int x, int y) {
   this.background =
       robot.createScreenCapture(
           new Rectangle(x, y, x + this.window.getWidth(), y + this.window.getHeight()));
 }
  public void takeScreenshot(boolean flag) {
    BufferedImage bufferedimage;
    try {
      Robot robot = new Robot();
      Point point = getLocationOnScreen();
      Rectangle rectangle = new Rectangle(point.x, point.y, getWidth(), getHeight());
      bufferedimage = robot.createScreenCapture(rectangle);
    } catch (Throwable throwable) {
      JOptionPane.showMessageDialog(
          frame, "An error occured while trying to create a screenshot!", "Screenshot Error", 0);
      return;
    }
    String s = null;
    try {
      s = getNearestScreenshotFilename();
    } catch (IOException ioexception) {
      if (flag) {
        JOptionPane.showMessageDialog(
            frame,
            "A screenshot directory does not exist, and could not be created!",
            "No Screenshot Directory",
            0);
        return;
      }
    }
    if (s == null && flag) {
      JOptionPane.showMessageDialog(
          frame,
          "There are too many screenshots in the screenshot directory!\n"
              + "Delete some screen\n"
              + "shots and try again.",
          "Screenshot Directory Full",
          0);
      return;
    }
    if (!flag) {
      final JFileChooser fileChooser = new JFileChooser();
      final JDialog fileDialog = createFileChooserDialog(fileChooser, "Save Screenshot", this);
      final BufferedImage si = bufferedimage;
      JFileChooser _tmp = fileChooser;
      fileChooser.setFileSelectionMode(0);
      fileChooser.addChoosableFileFilter(new imageFileFilter());
      fileChooser.setCurrentDirectory(new File("C:/.hack3rClient/Scre/"));
      fileChooser.setSelectedFile(new File(s));
      JFileChooser _tmp1 = fileChooser;
      fileChooser.setDialogType(1);
      fileChooser.addActionListener(
          new ActionListener() {

            public void actionPerformed(ActionEvent actionevent) {
              String s1 = actionevent.getActionCommand();
              if (s1.equals("ApproveSelection")) {
                File file = fileChooser.getSelectedFile();
                if (file != null && file.isFile()) {
                  int i =
                      JOptionPane.showConfirmDialog(
                          frame,
                          (new StringBuilder())
                              .append(file.getAbsolutePath())
                              .append(" already exists.\n" + "Do you want to replace it?")
                              .toString(),
                          "Save Screenshot",
                          2);
                  if (i != 0) {
                    return;
                  }
                }
                try {
                  ImageIO.write(si, "png", file);
                  // client.pushMessage("Screenshot taken.", 3, "@cr2@ Client");
                  // JOptionPane.showMessageDialog(frame,"Screenshot Taken");
                } catch (IOException ioexception2) {
                  JOptionPane.showMessageDialog(
                      frame,
                      "An error occured while trying to save the screenshot!\n"
                          + "Please make sure you have\n"
                          + " write access to the screenshot directory.",
                      "Screenshot Error",
                      0);
                }
                fileDialog.dispose();
              } else if (s1.equals("CancelSelection")) {
                fileDialog.dispose();
              }
            }

            {
            }
          });
      fileDialog.setVisible(true);
    } else {
      try {
        ImageIO.write(
            bufferedimage,
            "png",
            new File((new StringBuilder()).append("C:/.hack3rClient/Scre/").append(s).toString()));
        JOptionPane.showMessageDialog(
            frame,
            "Image has been saved to C:/.hack3rclient/Scre. You can view your images by pushing File>View Images in the menu dropdowns.",
            "Screenshot manager",
            JOptionPane.INFORMATION_MESSAGE);
        // client.pushMessage("Screenshot taken.", 3, "@cr2@ Client");
        // JOptionPane.showMessageDialog(frame,"Screenshot taken.");
      } catch (IOException ioexception1) {
        JOptionPane.showMessageDialog(
            frame,
            "An error occured while trying to save the screenshot!\n"
                + "Please make sure you have\n"
                + " write access to the screenshot directory.",
            "Screenshot Error",
            0);
      }
    }
  }
 /**
  * @time : 11:06:59 AM Sep 10, 2015 @Description : Get whole screen snapshot, result is stroed
  *     into screenImage
  * @throws AWTException
  */
 public void snapshotScreen(Dimension dimension) throws AWTException {
   Robot robot = new Robot();
   screenImage = robot.createScreenCapture(new Rectangle(dimension));
 }