Java实现截图并保存到本地

时间:2022-11-01 14:40:48
?

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 packagecom.credream.ocr;importjava.awt.Dimension;importjava.awt.Rectangle;importjava.awt.Robot;importjava.awt.Toolkit;importjava.awt.image.BufferedImage;importjava.io.File;importjavax.imageio.ImageIO;/******************************************************************************* * 该JavaBean可以直接在其他Java应用程序中调用,实现屏幕的"拍照" This JavaBean is used
to snapshot the
 * GUI in a Java application! You can embeded it in to your java application * source code, and us it to snapshot the right GUI of the application * * @see javax.ImageIO * @author liluqun ([email]liluqun@263.net[/email]) * @version 1.0 * ******************************************************************************/ publicclass
GuiCamera {
     privateString fileName; // 文件的前缀     privateString defaultName = "GuiCamera";     staticint
serialNum = 
0;
     privateString imageFormat; // 图像文件的格式     privateString defaultImageFormat = "jpg";     Dimension d = Toolkit.getDefaultToolkit().getScreenSize();      /***************************************************************************     * 默认的文件前缀为GuiCamera,文件格式为PNG格式 The default construct will
use the default
     * Image file surname "GuiCamera", and default image format "png"       **************************************************************************/    publicGuiCamera() {        fileName = defaultName;        imageFormat = defaultImageFormat;     }      /***************************************************************************     * @param s     *            the surname of the snapshot file     * @param format     *            the format of the image file, it can be "jpg" or "png"     *            本构造支持JPG和PNG文件的存储       **************************************************************************/    publicGuiCamera(String s, String format) {         fileName = s;        imageFormat = format;    }      /***************************************************************************     * 对屏幕进行拍照 snapShot the Gui once       **************************************************************************/    publicvoid
snapShot() {
         try{            // 拷贝屏幕到一个BufferedImage对象screenshot            BufferedImage screenshot = (newRobot())                    .createScreenCapture(newRectangle(00,                            (int) d.getWidth(), (int) d.getHeight()));            serialNum++;            // 根据文件前缀变量和文件格式变量,自动生成文件名            String name = fileName + String.valueOf(serialNum) + "."                    + imageFormat;            File f = newFile(name);            System.out.print("Save File " + name);            // 将screenshot对象写入图像文件            ImageIO.write(screenshot, imageFormat, f);            System.out.print("..Finished!\n");        catch(Exception ex) {            System.out.println(ex);        }    }     publicstatic
void
main(String[] args) {
        GuiCamera cam = newGuiCamera("d:\\qq""bmp");//        cam.snapShot();    }}

第二种方法:

原文地址:Java实现截图并保存到本地

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 packagecom.credream.ocr; importjava.awt.AWTException;importjava.awt.Color;importjava.awt.Dimension;importjava.awt.Graphics;importjava.awt.GraphicsDevice;importjava.awt.GraphicsEnvironment;importjava.awt.Rectangle;importjava.awt.Robot;importjava.awt.Toolkit;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;importjava.awt.event.MouseMotionAdapter;importjava.awt.image.BufferedImage;importjava.awt.image.RescaleOp;importjava.io.File;importjava.io.IOException;importjava.text.SimpleDateFormat;importjava.util.Date;importjavax.imageio.ImageIO;importjavax.swing.JFrame;importjavax.swing.filechooser.FileSystemView; /** * java截屏 * 运行后将当前屏幕截取,并最大化显示。 * 拖拽鼠标,选择自己需要的部分。 * 按Esc键保存图片到桌面,并退出程序。 * 点击右上角(没有可见的按钮),退出程序,不保存图片。 * * @author JinCeon */publicclass
SnapshotTest {
    publicstatic
void
main(String[] args) {
        // 全屏运行        RectD rd = newRectD();        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()                .getDefaultScreenDevice();        gd.setFullScreenWindow(rd);    }}  classRectD extendsJFrame {    privatestatic
final
long serialVersionUID = 1L;
    intorgx, orgy, endx, endy;    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();    BufferedImage image;    BufferedImage tempImage;    BufferedImage saveImage;    Graphics g;      @Override    publicvoid
paint(Graphics g) {
        RescaleOp ro = newRescaleOp(0.8f, 0null);        tempImage = ro.filter(image, null);        g.drawImage(tempImage, 00this);    }      publicRectD() {        snapshot();        setVisible(true);        // setSize(d);//最大化窗口        setDefaultCloseOperation(EXIT_ON_CLOSE);        this.addMouseListener(newMouseAdapter() {            publicvoid
mousePressed(MouseEvent e) {
                orgx = e.getX();                orgy = e.getY();            }        });        this.addMouseMotionListener(newMouseMotionAdapter() {            publicvoid
mouseDragged(MouseEvent e) {
                endx = e.getX();                endy = e.getY();                g = getGraphics();                g.drawImage(tempImage, 00, RectD.this);                intx = Math.min(orgx, endx);                inty = Math.min(orgy, endy);                intwidth = Math.abs(endx - orgx)+1;                intheight = Math.abs(endy - orgy)+1;                // 加上1,防止width或height为0                g.setColor(Color.BLUE);                g.drawRect(x-1, y-1, width+1, height+1);                //减1,加1都是为了防止图片将矩形框覆盖掉                saveImage = image.getSubimage(x, y, width, height);                g.drawImage(saveImage, x, y, RectD.this);            }        });        this.addKeyListener(newKeyAdapter() {            @Override            publicvoid
keyReleased(KeyEvent e) {
                // 按Esc键退出                if(e.getKeyCode() == 27) {                    saveToFile();                    System.exit(0);                }            }        });    }      publicvoid
saveToFile() {
        SimpleDateFormat sdf = newSimpleDateFormat("yyyymmddHHmmss");        String name = sdf.format(newDate());        File path = FileSystemView.getFileSystemView().getHomeDirectory();        String format = "jpg";        File f = newFile(path + File.separator + name + "."+ format);        try{            ImageIO.write(saveImage, format, f);        catch(IOException e) {            e.printStackTrace();        }    }      publicvoid
snapshot() {
        try{            Robot robot = newRobot();            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();            image = robot.createScreenCapture(newRectangle(00, d.width,                    d.height));        catch(AWTException e) {            e.printStackTrace();        }    }}
第三种方法:
?
1234567891011121314151617181920212223242526 packagecom.credream.robotExp; importjava.awt.AWTException;importjava.awt.Rectangle;importjava.awt.Robot;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.IOException;importjavax.imageio.ImageIO;publicclass
RobotExp {
publicstatic
void
main(String[] args) {
try{Robot
robot = 
newRobot();
BufferedImage
bi=robot.createScreenCapture(
newRectangle(900,800)); // 根据指定的
 区域(1300,800)抓取屏幕的指定区域ImageIO.write(bi, "jpg"newFile("D:/imageTest.jpg")); //把抓取到的内容写入到一 个jpg文件中catch(AWTException e) {e.printStackTrace();catch(IOException e) {e.printStackTrace();}}}