java代码实现截图功能(屏幕截图)
程序员文章站
2024-02-19 11:18:28
复制代码 代码如下:import java.awt.dimension;import java.awt.rectangle;import java.awt.robot;im...
复制代码 代码如下:
import java.awt.dimension;
import java.awt.rectangle;
import java.awt.robot;
import java.awt.toolkit;
import java.awt.image.bufferedimage;
import java.io.file;
import javax.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
* @version 1.0
*****************************************************/
public class test
{
private string filename; //文件的前缀
private string defaultname = "guicamera";
static int serialnum=0;
private string imageformat; //图像文件的格式
private string defaultimageformat="png";
dimension d = toolkit.getdefaulttoolkit().getscreensize();
/****************************************************************
* 默认的文件前缀为guicamera,文件格式为png格式
* the default construct will use the default
* image file surname "guicamera",
* and default image format "png"
****************************************************************/
public test() {
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文件的存储
****************************************************************/
public test(string s,string format) {
filename = s;
imageformat=format;
}
/****************************************************************
* 对屏幕进行拍照
* snapshot the gui once
****************************************************************/
public void snapshot() {
try {
//拷贝屏幕到一个bufferedimage对象screenshot
bufferedimage screenshot = (new robot()).createscreencapture(new
rectangle(0, 0, (int) d.getwidth(), (int) d.getheight()));
serialnum++;
//根据文件前缀变量和文件格式变量,自动生成文件名
string name=filename+string.valueof(serialnum)+"."+imageformat;
file f = new file(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);
}
}
public static void main(string[] args)
{
test cam= new test("d:\\hello", "png");//
cam.snapshot();
}
}