首页 > 代码库 > Java代码截屏

Java代码截屏

使用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();
		}

	}

}


Java代码截屏