java仿QQ截图 收藏

时间:2022-08-18 15:26:19
Test.java
/**
 * 用Java模拟出QQ桌面截图功能
 * @author  ZengYanHui , the student comes from Guang Dong Ocean University
 */
package edu.captureimage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
public class Test extends JFrame{
   private static final long serialVersionUID = -267804510087895906L;
   public static JFrame mainwindow = null; //主窗体
  
   public Test(){
     try {
         //new ScreenWindow();
     } catch (Exception e1) {
       JOptionPane.showConfirmDialog(null, "出现意外错误!", "系统提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
     }
     setSize(200,300);
     setVisible(true);
    
    
     //同时按下CTRL+ALT+A按键事件
     KeyboardFocusManager manager =  KeyboardFocusManager.getCurrentKeyboardFocusManager();
     manager.addKeyEventPostProcessor(new KeyEventPostProcessor(){
   @Override
   public boolean postProcessKeyEvent(KeyEvent e) {
    // TODO Auto-generated method stub
    //判断是否同时按下CTRL+ALT+A , 若是则进行截图
          if(e.isAltDown() && e.isControlDown() && e.getKeyCode() == KeyEvent.VK_A){
           try {
             setVisible(false);
                new ScreenWindow(mainwindow);
           } catch (Exception e1) {
             JOptionPane.showConfirmDialog(null, "出现意外错误!", "系统提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
           } 
          }
    return false;
   }
      
     });
   }
   public static void main(String[] args) {
    mainwindow = new Test();
   }
}

 
 
 
 
ScreenWindow.java
/**
 * 用Java模拟出QQ桌面截图功能
 * @author  ZengYanHui , the student comes from Guang Dong Ocean University
 */
package edu.captureimage;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ScreenWindow extends JFrame {
 private static final long serialVersionUID = -3758062802950480258L;
 
 public Dimension screenDims = null;  //屏幕大小
 
 private boolean isDrag = false;
 private int x = 0;
 private int y = 0;
 private int xEnd = 0;
 private int yEnd = 0;
 
 public ImageIcon screenImageIcon = null;
 
 public JLabel label = null;
 
 public JFrame copy_mainwindow;  //引用 mainwindow 主窗体对象,mainwindow即为调用该截图模块的JFrame对象
 public ScreenWindow(JFrame mainwindow) throws AWTException, InterruptedException {
     screenDims = Toolkit.getDefaultToolkit().getScreenSize();
     screenImageIcon = new ImageIcon(ScreenImage.getScreenImage(0, 0, screenDims.width, screenDims.height));
     label = new JLabel(screenImageIcon);
     label.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
     copy_mainwindow = mainwindow;
    
     //按键ESC退出事件
     KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
     manager.addKeyEventPostProcessor(new KeyEventPostProcessor() {
       @Override
       public boolean postProcessKeyEvent(KeyEvent e) {
          if (KeyEvent.VK_ESCAPE == e.getKeyCode()) { //判断是否按下ESC键
              dispose();
              copy_mainwindow.setVisible(true);
          }
          return false;
       }
      
     });
         
     label.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
          if (e.getButton() == MouseEvent.BUTTON3) {
            dispose();
          }
        }
        public void mousePressed(MouseEvent e) {
          x = e.getX();
          y = e.getY();
        }
        public void mouseReleased(MouseEvent e) {
          if (isDrag) {
            xEnd = e.getX();
            yEnd = e.getY();
            if(x > xEnd){
              int temp = x;
              x = xEnd;
              xEnd = temp;
            }
            if(y > yEnd){
              int temp = y;
              y = yEnd;
              yEnd = temp;
            }
           
            //保存文件
            try {
               JFileChooser filechooser = new JFileChooser();
               //设置主目录
              // filechooser.setCurrentDirectory(new File("C:\\Users\\miklejhon\\Desktop"));
               //弹出保存文件的选择框
               int result = filechooser.showSaveDialog(null);
               //保存文件
               if(result==JFileChooser.APPROVE_OPTION){
               File selectedfile = filechooser.getSelectedFile();
               File file = new File(selectedfile.getPath());
                  FileOutputStream fos = new FileOutputStream(file);
                  BufferedImage bufferedimage = new BufferedImage(xEnd - x,yEnd - y,BufferedImage.TYPE_INT_BGR);
                  Image image = ScreenImage.getScreenImage(x, y, xEnd - x, yEnd - y);
                  Graphics g = bufferedimage.getGraphics();
                  g.drawImage(image,0, 0,xEnd - x,yEnd - y,null);
                  g.setColor(Color.white);
                  g.drawRect(0, 0, xEnd - x, yEnd - y);
                  ImageIO.write(bufferedimage, "JPEG",fos);
                  fos.flush();
                  fos.close();
                 
                  dispose();
                  copy_mainwindow.setVisible(true);
               }else{
                label.setIcon(screenImageIcon);
               }
            } catch (Exception ex) {
               ex.printStackTrace();
               JOptionPane.showConfirmDialog(null, "出现意外错误!", "系统提示", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
            }
          }
       }
  });
    
  //鼠标拖曳事件  
  label.addMouseMotionListener(new MouseMotionAdapter() {
     public void mouseDragged(MouseEvent e) {
        if(!isDrag){
            isDrag = true;
        }
        //拖动过程的虚线选取框实现
        int endx = e.getX();
        int endy = e.getY();
        BufferedImage bufferedimage = new BufferedImage(screenDims.width, screenDims.height,BufferedImage.TYPE_INT_BGR);
        Graphics g = bufferedimage.getGraphics();
        g.drawImage(screenImageIcon.getImage(),0, 0,screenDims.width,screenDims.height,null);
        g.setColor(Color.red);
        g.drawRect(x, y, endx-x, endy-y);
        label.setIcon(new ImageIcon(bufferedimage));
     }
  });
 
  this.setUndecorated(true);
  this.getContentPane().add(label);
  this.setSize(screenDims.width, screenDims.height);
  this.setVisible(true);
  this.setExtendedState(JFrame.MAXIMIZED_BOTH);
 }
}
class ScreenImage {
  //截图
  public static Image getScreenImage(int x, int y, int w, int h) throws AWTException, InterruptedException {
     Robot robot = new Robot();
     Image screen = robot.createScreenCapture(new Rectangle(x, y, w, h)).getScaledInstance(w, h, Image.SCALE_SMOOTH);
     MediaTracker tracker = new MediaTracker(new Label());
     tracker.addImage(screen, 1);
     tracker.waitForID(0);
     return screen;
  }
}