Simple como dice el título: ¿Se pueden usar solo comandos de Java para tomar una captura de pantalla y guardarla? O bien, ¿necesito usar un programa específico del sistema operativo para tomar la captura de pantalla y luego sacarlo del portapapeles?¿Hay alguna forma de tomar una captura de pantalla con Java y guardarla en algún tipo de imagen?
Respuesta
Lo creas o no, en realidad puedes usar java.awt.Robot
para "crear una imagen que contenga píxeles leídos de la pantalla". Luego puede escribir esa imagen en un archivo en el disco.
yo sólo lo han probado, y toda la cosa termina como:
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(args[0]));
NOTA: Esto sólo capturar el monitor principal. Consulte GraphicsConfiguration para obtener soporte para monitores múltiples.
Nunca me hubiera encontrado con java.awt.Robot. Esa es una clase impresionante y útil. –
Me pregunto si esto es lo que usan las aplicaciones para compartir pantallas como Elluminate (http://www.elluminate.com/). –
¿Funcionará incluso si no tengo consola? –
nunca me ha gustado el uso del robot, así que hice mi propio método simple para hacer capturas de pantalla de los objetos JFrame:
public static final void makeScreenshot(JFrame argFrame) {
Rectangle rec = argFrame.getBounds();
BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
argFrame.paint(bufferedImage.getGraphics());
try {
// Create temp file
File temp = File.createTempFile("screenshot", ".png");
// Use the ImageIO API to write the bufferedImage to a temporary file
ImageIO.write(bufferedImage, "png", temp);
// Delete temp file when program exits
temp.deleteOnExit();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
¿Alguna razón de por qué no te gusta Robot? –
Piense en ello simplemente como una cuestión de gusto. – DejanLekic
Parece que esto debería tener la ventaja de funcionar incluso si la ventana de destino está oscurecida antes de que se tome la captura de pantalla. –
public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
Si desea capturar todos los monitores, que puede utilizar el siguiente código :
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);
sería mejor calcularla [de esta manera] (http://stackoverflow.com/a/13380999/446591) –
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
public class HelloWorldFrame extends JFrame implements ActionListener {
JButton b;
public HelloWorldFrame() {
this.setVisible(true);
this.setLayout(null);
b = new JButton("Click Here");
b.setBounds(380, 290, 120, 60);
b.setBackground(Color.red);
b.setVisible(true);
b.addActionListener(this);
add(b);
setSize(1000, 700);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == b)
{
this.dispose();
try {
Thread.sleep(1000);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
Rectangle rec = new Rectangle(0, 0, d.width, d.height);
Robot ro = new Robot();
BufferedImage img = ro.createScreenCapture(rec);
File f = new File("myimage.jpg");//set appropriate path
ImageIO.write(img, "jpg", f);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
HelloWorldFrame obj = new HelloWorldFrame();
}
}
Hice un punto de referencia y este es el más lento, también tiene la mayor pérdida y el mayor tamaño de archivo. Lo siento, –
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);
allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);
}
Robot robot = new Robot();
BufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);
File file = new File("C:\\Users\\Joe\\Desktop\\scr.png");
if(!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ImageIO.write(bufferedImage, "png", fos);
bufferedIma ge contendrá una captura de pantalla completa, esto se probó con tres monitores
Puede usar java.awt.Robot
para realizar esta tarea.
a continuación se muestra el código del servidor, que guarda la captura de pantalla capturada como imagen en su Directorio.
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();
}
}
}
Y este es el código de cliente que se ejecuta en el hilo y después de algunos minutos que está capturando la captura de pantalla de la pantalla del usuario.
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();
}
}
- 1. ¿Cómo puedo tomar una captura de pantalla y guardarla como JPEG en Windows?
- 2. ¿Hay alguna manera de tomar una captura de pantalla en MS-Access con vba?
- 3. Cómo tomar una captura de pantalla en OpenGL
- 4. Tomar una captura de pantalla con Pyglet [Fix'd]
- 5. Cómo tomar una captura de pantalla con FireMonkey (multiplataformas)
- 6. ¿Hay alguna manera de tomar una captura de pantalla del escritorio de Windows del usuario?
- 7. ¿Cómo tomar una captura de pantalla de una página web?
- 8. Tomar una captura de pantalla parcial en el iPad
- 9. Tomar captura de pantalla de una página web (remota) programáticamente
- 10. La forma más rápida de tomar una captura de pantalla con Python en Windows
- 11. ¿Cómo tomar una captura de pantalla con unidad HTML?
- 12. Sin iPhone, ¿cómo tomar una captura de pantalla con XCode?
- 13. cómo tomar una captura de pantalla del iPhone programáticamente?
- 14. ¿Cómo tomar la captura de pantalla programáticamente?
- 15. Tomar una captura de pantalla de área específica
- 16. ¿Hay alguna manera de tomar automáticamente una captura de pantalla de un sitio web a través de una URL?
- 17. Captura de impresiones de pantalla en Java
- 18. ¿Hay alguna forma de fundición "tipo segura" en Java?
- 19. Selenium 2 (webdriver): Tomar una captura de pantalla devuelve una imagen negra
- 20. ¿Cómo puedo tomar una captura de pantalla/imagen de un sitio web usando Python?
- 21. Tomar una captura de pantalla mediante programación combinando los elementos de OpenGL y UIKit
- 22. C#: cómo tomar una captura de pantalla de una parte de la pantalla
- 23. Captura de pantalla de la pantalla actual
- 24. Imagen de captura de pantalla en C++ en OSX
- 25. ¿Hay alguna forma de tomar una clase o biblioteca C# y convertirla automáticamente en Visio?
- 26. Cómo tomar capturas de pantalla rápidamente en Java?
- 27. ¿Hay alguna forma de que PHP detecte una imagen dañada?
- 28. ¿Cómo tomar una captura de pantalla de iPhone de toda la vista, incluidas las partes fuera de la pantalla?
- 29. ¿Hay alguna otra manera que no sea el método de miniaturas para tomar una captura de pantalla de un video en Iphone?
- 30. ¿Cómo puedo tomar una captura de pantalla de un sitio web con .NET?
Nunca pensé que sería tan simple. – jjnguy
Gracias a esta pregunta, escribí un tutorial para principiantes absolutos en mi blog: http://www.thepcwizard.in/2012/12/java-screen-capturing-tutorial.html – ThePCWizard
http://web.archive.org /web/20090204074007/http://schmidt.devlib.org/java/save-screenshot.html –