Javaコードスクリーンショット

2769 ワード

Javaを使用して、Robotというクラスを利用してソフトウェアのスクリーンショットを実現することができます.コードは以下の通りです.
package test;

import java.awt.AWTException;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;

public class TestRobot {

	private static Robot bt;
	private static GraphicsDevice gd;
	static {
		GraphicsEnvironment ge = GraphicsEnvironment
				.getLocalGraphicsEnvironment();
		GraphicsDevice[] gs = ge.getScreenDevices();
		gd = gs[0];
		try {
			bt = new Robot(gd);
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}

	public static void test1() {
		try {
			DisplayMode mode = gd.getDisplayMode();
			int width = mode.getWidth();
			int height = mode.getHeight();
			System.out.println(width + "x" + height);
			BufferedImage img = bt.createScreenCapture(new Rectangle(width,
					height));
			Date date = new Date();
			//                   
			FileOutputStream fos = new FileOutputStream("/home/qcq/" + date.getTime()
					+ ".jpg");
			ImageIO.write(img, "jpeg", fos);
			fos.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	public static void main(String[] args) {

		SystemTray tray = SystemTray.getSystemTray();//create the tray
		try {
			//           。
			Image image = ImageIO.read(new File("src/1.jpg"));
			PopupMenu menu = new PopupMenu();
			MenuItem m1 = new MenuItem("  ");
			MenuItem m0 = new MenuItem("  ");
			menu.add(m1);
			menu.add(m0);
			TrayIcon trayIcon = new TrayIcon(image, "  ", menu);
			tray.add(trayIcon);
			
			m1.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					test1();
				}
			});
			m0.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					System.exit(0);
				}
			});
			//          (Windows)。linux  ,        。
			bt.keyPress(KeyEvent.VK_WINDOWS);
			bt.keyPress(KeyEvent.VK_D);
			bt.keyRelease(KeyEvent.VK_WINDOWS);
			bt.keyRelease(KeyEvent.VK_D);
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (AWTException e) {
			e.printStackTrace();
		}

	}

}