开博第一篇,贴一篇java截图代码
/*********************************
* 本类用来完成截图的动作
* 主类通过mode和path来控制本类的动作
*
* @author 陈尧
*
* @version 0.1
*
* @date 2008/5/26
*********************************/
package chenyao;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
public class Snap {
private String path; // 保存路径
private String mode; // 保存格式
private String nameFormat = "yyMMddhhmmss"; // 文件命名格式
private int x1; // 左上点x
private int y1; // 左上点y
private int x2; // 右下点x
private int y2; // 右下点y
public Snap(String path, String mode) {
this.path = path;
this.mode = mode;
}
public Snap(String path, String mode, int x1, int y1, int x2, int y2) {
this.path = path;
this.mode = mode;
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
/**
* 截图方法
*
* @return 返回截图是否成功
*/
public boolean snapPhoto() {
try {
// 构造Robot,用来获得选定区域的图像
Robot robot = new Robot();
Toolkit toolkit = Toolkit.getDefaultToolkit();
int width = toolkit.getScreenSize().width;
int height = toolkit.getScreenSize().height;
// 构造BufferedImage输出图像
BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0,
width, height));
return output(image);
} catch (Exception e) {
System.out.println("截图失败!");
return false;
}
}
public boolean snapArea() {
try {
// 构造Robot,用来获得选定区域的图像
Robot robot = new Robot();
// 构造BufferedImage输出图像
BufferedImage image = robot.createScreenCapture(new Rectangle(x1, y1,
(x2 - x1), (y2 - y1)));
return output(image);
} catch (Exception e) {
System.out.println("截图失败!");
return false;
}
}
/**
* 按选定格式输出文件
*
* @param image
* @return 返回文件是否生成成功
*/
public boolean output(BufferedImage image) {
// 用当前时间来命名
Date time = new Date();
// 时间格式
SimpleDateFormat format = new SimpleDateFormat(nameFormat);
// 输出文件
try {
if (mode.contains("png")) {
ImageIO.write(image, "png", new File(path + format.format(time) + ".png"));
}
if (mode.contains("bmp")) {
ImageIO.write(image, "bmp", new File(path + format.format(time) + ".bmp"));
}
if (mode.contains("gif")) {
ImageIO.write(image, "gif", new File(path + format.format(time) + ".gif"));
}
if (mode.contains("jpg")) {
ImageIO.write(image, "jpg", new File(path + format.format(time) + ".jpg"));
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}