Java實現簡單的截圖工具

hollistertop 8年前發布 | 5K 次閱讀 Java

Robot.rar ~ 116KB         

ScreenShot.java ~ 420B         

package Robot_Caputer;

import java.awt.AWTException;
import java.awt.EventQueue;

public class ScreenShot {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {


            public void run() {

                try{
                    ScreenShotWindow ssw=new ScreenShotWindow();
                    ssw.setVisible(true);
                }catch(AWTException e){
                    e.printStackTrace();
                }
            }
        });
    }



}

[文件] ScreenShotWindow.java ~ 5KB     (13)    

package Robot_Caputer;
import images.*;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
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.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JWindow;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

//Jwindow 也是四大頂級組件之一,地位等同于JFrame,是一個無標題欄的窗口
public class ScreenShotWindow extends JWindow {



    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private int orgx,orgy,endx,endy;

    /**image的作用:
     * 1.獲取整個屏幕的截圖*/
    private BufferedImage image=null;
    private BufferedImage tempImage=null;
    private BufferedImage saveImage=null;

    private ToolsWindow tools=null;


    public ScreenShotWindow() throws AWTException {

        //獲取默認屏幕設備
        GraphicsEnvironment environment=GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice screen=environment.getDefaultScreenDevice();

        //獲取屏幕尺寸
        Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
        this.setBounds(0, 0, d.width, d.height);
        //獲取屏幕截圖
        Robot robot=new Robot(screen);
//      Robot robot=new Robot();

//      image=new BufferedImage((int)d.getWidth(),(int)d.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);
        image=robot.createScreenCapture(new Rectangle(0, 0, d.width, d.height));

        //設置鼠標敲擊的時間監聽
        this.addMouseListener(new MouseAdapter() {

            //鼠標按下的事件監聽
            @Override
            public void mousePressed(MouseEvent e) {

                //
                orgx=e.getX();
                orgy=e.getY();

                if(tools!=null){
                    tools.setVisible(false);
                }
            }

            //鼠標抬起的事件監聽
            @Override
            public void mouseReleased(MouseEvent e) {

                if(tools==null){
                    tools=new ToolsWindow(ScreenShotWindow.this,e.getX(),e.getY());

                }else{
                    tools.setLocation(e.getX(), e.getY());
                }
                tools.setVisible(true);
                tools.toFront();

            }

        });

        //對于鼠標移動的監聽
        this.addMouseMotionListener(new MouseMotionAdapter() {

            //鼠標滑動的監聽
            //在滑動過程中會被反復調用
            @Override
            public void mouseDragged(MouseEvent e) {

                endx=e.getX();
                endy=e.getY();

                //臨時圖像,用于緩沖屏幕區域放置屏幕閃爍
                Image tempImage2=createImage(ScreenShotWindow.this.getWidth(),ScreenShotWindow.this.getHeight());
                //用于繪圖
                Graphics g=tempImage2.getGraphics();
                g.drawImage(tempImage, 0, 0,null);

                int x=Math.min(orgx, endx);
                int y=Math.min(orgy, endy);

                int width=Math.abs(endx-orgx)+1;
                int height=Math.abs(endy-orgy)+1;

                g.setColor(Color.RED);
                //保證圖片矩形不被邊框覆蓋
                g.drawRect(x-1, y-1, width+1, height+1);

                //getSubimage(int x,int y,int w,int h)用于返回規定位置中的矩形圖像到BufferedImag對象中
                saveImage=image.getSubimage(x, y, width, height);
                //用于畫當前圖像中的可用圖像
                g.drawImage(saveImage, x, y, null);

                ScreenShotWindow.this.getGraphics().drawImage(tempImage2,
                        0, 0,ScreenShotWindow.this);

            }


        });

    }

    //重寫了繪畫的方法
    @Override
    public void paint(Graphics g) {

        //new RescaleOp(float[] scaleFactors, float[] offsets, RenderingHints hints)
        //構造一個具有所希望的縮放因子和偏移量的新 RescaleOp。
        //RescaleOp 是有關圖像縮放的類
        //RescaleOp.filter(BufferedImage src,BufferedImage dest)
        //用于對源圖像src進行縮放
        RescaleOp ro=new RescaleOp(0.8f,0, null);
        tempImage=ro.filter(image, null);
        g.drawImage(tempImage, 0, 0, this);

    }
    //保存圖像到文件
    public void saveImage() throws IOException{
        JFileChooser jfc=new JFileChooser();
        jfc.setDialogTitle("保存");

        //文件過濾器,用戶過濾可選擇的文件
        FileNameExtensionFilter filter=new FileNameExtensionFilter("JPG", "jpg");
        jfc.setFileFilter(filter);

        //初始化一個默認文件(此文件會生成在桌面)

        SimpleDateFormat sdf=new SimpleDateFormat("yyyymmddHHmmss");
        String filename=sdf.format(new Date());

        File filePath=FileSystemView.getFileSystemView().getHomeDirectory();
        File defaultFile=new File(filePath+File.separator+filename+".jpg");
        jfc.setSelectedFile(defaultFile);

        int flag=jfc.showSaveDialog(this);
        if(flag==JFileChooser.APPROVE_OPTION){
            File file=jfc.getSelectedFile();
            String path=file.getPath();
            //檢查文件后綴,放置用戶忘記輸入后綴或輸入不正確的后綴
            if(!(path.endsWith(".jpg")||path.endsWith("JPG"))){
                path+=".jpg";
            }
            //寫入文件
            ImageIO.write(saveImage, "jpg", new File(path));
            System.exit(0);
        }
    }

}

[文件] ToolsWindow.java ~ 1KB         

package Robot_Caputer;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOError;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JToolBar;
import javax.swing.JWindow;

public class ToolsWindow extends JWindow{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private ScreenShotWindow parent;

    public ToolsWindow(ScreenShotWindow parent,int x,int y) {

        this.parent=parent;
        this.init();
        //將組件移到(x,y)的位置
        this.setLocation(x, y);
        //調整窗口的大小來適應控件
        this.pack();
        this.setVisible(true);
    }

    private void init() {

        this.setLayout(new BorderLayout());
        JToolBar toolBar=new JToolBar("Java截圖");


        //保存按鈕
        JButton saveButton=new JButton(new ImageIcon("src/images/SaveIcon.gif"));
        saveButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                try{
                    parent.saveImage();
                }catch(IOException ex1){
                    ex1.printStackTrace();

                }
            }
        });
        toolBar.add(saveButton);

        //關閉按鈕
        JButton closedButton=new JButton(new ImageIcon("src/images/closedIcon.gif"));
        closedButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                System.exit(0);
            }
        });
        toolBar.add(closedButton);

        this.add(toolBar, BorderLayout.NORTH);

    }
}
 本文由用戶 hollistertop 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!