由于工作业务需要,需自己编写一个java截图的小程序,参考过许多网上的文章,但是都感觉不太合适,所以就自己开发一个吧。该小程序主要功能有三 个:
1.区域截图;
2.定时截图;
3.通过截图自动生成gif动图;
好了废话不多说,直接上代码:
注释很清楚,我就不一一解释了,可自行查看
ScreenWindow.java文件:
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import demo.AnimatedGifEncoder;
public class ScreenWindow extends JFrame {
private static final long serialVersionUID = -3758062802950480258L;
private Image image;
private JLabel imageLabel;
private int times;//截图次数
private int intervaltime;//截图间隔时间(毫秒)
private ArrayList<String> filenames;
//将截图的图像加载到的目标组件,用于传值
private JLabel targetLabel;
private int x, y, xEnd, yEnd; //用于记录鼠标点击开始和结束的坐标
public ScreenWindow(JLabel targetLabel,int times,int intervaltime) throws AWTException, InterruptedException {
//目标组件初始化
this.targetLabel = targetLabel;
this.times = times;
this.intervaltime = intervaltime;
this.filenames = new ArrayList<String>();
//取得屏幕尺寸
Dimension screenDims = Toolkit.getDefaultToolkit().getScreenSize();
//取得全屏幕截图
image = getScreenImage(0, 0, screenDims.width, screenDims.height);
//用于展示截图
imageLabel = new JLabel(new ImageIcon(image));
//当鼠标在imageLabel上时,展示为 十字形
imageLabel.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
createAction();
this.getContentPane().add(imageLabel);
this.setUndecorated(true); //去掉窗口装饰
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setExtendedState(JFrame.MAXIMIZED_BOTH); //窗口最大化
}
/**
* 实现监听动作
*/
private void createAction() {
Timer timer = new Timer();
//鼠标截图监听
imageLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON3) { //鼠标右键单击事件
//退出ScreenWindow
ScreenWindow.this.dispose();
timer.cancel();
}
}
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseReleased(MouseEvent e) {
xEnd = e.getX();
yEnd = e.getY();
timer.schedule(new TimerTask() {
int i = 1;
@Override
public void run() {
if(i<=times){
try {
//鼠标弹起时,取得鼠标起始两点组成的矩形区域的图像
//因为 xEnd 可能比 x 小 (由右网左移动)起始坐标取其中较小值,xEnd - x 取其绝对值, 同样处理y
image = getScreenImage(Math.min(x, xEnd), Math.min(y, yEnd), Math.abs(xEnd - x), Math.abs(yEnd - y));
DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String formatDate = format.format(new Date());
String fileName = formatDate;
filenames.add(i-1, fileName);
System.out.println("执行开始:"+i);
// ImageIO.write((BufferedImage)image, "png", new File("E:\\image\\"+fileName+i+".png"));
ImageIO.write((BufferedImage)image, "png", new File("E:\\image\\"+fileName+".png"));
//将所截得的图像,加载到目标组件targetLabel
targetLabel.setIcon(new ImageIcon(image));
//退出该ScreenWindow
ScreenWindow.this.dispose();
//TODO 生成gif图
if(filenames.size()==times){
System.out.println("开始生成gif图:");
AnimatedGifEncoder e = new AnimatedGifEncoder();
e.setRepeat(0);
e.start("E:\\gifs\\"+fileName+".gif");
for(int j=0;j<times;j++){
//读入文件
BufferedImage src = ImageIO.read(new File("E:\\image\\"+filenames.get(j)+".png"));
//设置gif图片帧数
e.setDelay(1000);
//将图片添加进gif图
e.addFrame(src);
}
e.finish();
System.out.println("合成gif图完成!");
}
} catch (Exception e) {
e.printStackTrace();
}
i++;
}else{
timer.cancel();
}
}
},0, intervaltime);
}
});
System.out.println("选择区域结束,开始截图···");
//截屏时用于显示截屏区域线框
imageLabel.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
//1. 取得鼠标的按下点和移动当前点坐标
xEnd = e.getX();
yEnd = e.getY();
//2. 创建一个缓冲图形对象(BufferedImage) bi
BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D)bi.getGraphics();
//3. 将原始图形画到 bi 中
g2d.drawImage(image, 0, 0, null);
g2d.setColor(Color.RED); //设置画笔颜色为红色
//4. 根据取得的坐标画一个矩形到 bi 中
//以鼠标按下点坐标和鼠标拖动的当前点坐标画矩形,作为截图区域的展示
//+1 与 -1 是为了防止截图时将矩形框也截进去
g2d.drawRect(Math.min(x, xEnd) - 1, Math.min(y, yEnd) - 1, Math.abs(xEnd - x) + 1, Math.abs(yEnd - y) + 1);
g2d.dispose();
//5. 将 bi 画到屏幕上
Graphics g = imageLabel.getGraphics();
g.drawImage(bi, 0, 0, null);
g.dispose();
}
public void mouseMoved(MouseEvent e) {
}
});
}
public BufferedImage getScreenImage(int x, int y, int w, int h) throws AWTException, InterruptedException {
Robot robot = new Robot();
BufferedImage screen = robot.createScreenCapture(new Rectangle(x, y, w, h));
return screen;
}
// public static void main(String[] args) throws AWTException, InterruptedException {
// new ScreenWindow();
// }
}
SnapShoot.java文件(界面设置):
package test;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
/**
* 屏幕截图小程序
* 界面设置
*
*/
public class SnapShoot extends JFrame {
private static final long serialVersionUID = 1L;
private JButton snapButton;
private JLabel imageLabel;
private JTextField tf1,tf2;
public SnapShoot(){
snapButton = new JButton("开始截图(请选择区域)");
imageLabel = new JLabel();
//用于显示文字
JLabel tex1 = new JLabel("间隔时间:");
//创建文本区域组件
tf1 = new JTextField("1");
//用于显示文字及上个组件的单位
JLabel tex2 = new JLabel("s 持续时间:");
//创建文本区域组件
tf2 = new JTextField("10");
//用于显示持续时间的单位“s”
JLabel tex3 = new JLabel("s");
JPanel pane = new JPanel();
//用于在面板上显示截图
pane.add(imageLabel);
//用于显示截图的区域
JScrollPane imgScrollPane = new JScrollPane(pane);
//容器布局
Container container = this.getContentPane();
container.setLayout(null);
//设置组件字体样式及大小
snapButton.setFont(new Font("谐体",Font.BOLD,12));
tex1.setFont(new Font("谐体",Font.PLAIN,14));
tex2.setFont(new Font("谐体",Font.PLAIN,14));
tex3.setFont(new Font("谐体",Font.PLAIN,14));
//设置文本水平的对齐方式
tf1.setHorizontalAlignment(JTextField.CENTER);
tf2.setHorizontalAlignment(JTextField.CENTER);
//组件设置绝对定位
snapButton.setBounds(10, 10, 160, 20);
tex1.setBounds(180, 10, 60, 20);
tf1.setBounds(245, 10, 20, 20);
tex2.setBounds(265, 10, 85, 20);
tf2.setBounds(350, 10, 25, 20);
tex3.setBounds(375, 10, 10, 20);
imgScrollPane.setBounds(10, 40, 565, 300);
//将各个组件添加到框架中
this.add(snapButton);
this.add(tex1);
this.add(tf1);
this.add(tex2);
this.add(tf2);
this.add(tex3);
this.add(imgScrollPane);
createAction();
//设置框架属性
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 400);
this.setTitle("截图小工具");
this.setLocationRelativeTo(null); //居中
this.setVisible(true);
}
private void createAction() {
snapButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
//开启模拟屏幕,将显示截图的目标组件传入
System.out.println("开始截图");
String interval = tf1.getText();//截图间隔时间
String times = tf2.getText();//截图次数
int intervaltime = Integer.valueOf(interval)*1000;//传入参数转化为毫秒
int tms = Integer.valueOf(times);
new ScreenWindow(imageLabel,tms,intervaltime);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
public static void main(String[] args) {
//截图
new SnapShoot();
}
}
大家可自行检测。