Posted on 2009-08-09 23:40
songk 阅读(384)
评论(0) 编辑 收藏
以下方式可获取(利用GC类的copyArea方法):
Image screenImage = new Image(display, display.getBounds());
new GC(display).copyArea(screenImage, 0, 0);
以下一个小Demo,运行后可将桌面图像存入当前目录:
1 import java.io.ByteArrayOutputStream;
2 import java.io.File;
3 import java.io.FileOutputStream;
4 import java.io.IOException;
5
6 import org.eclipse.swt.SWT;
7 import org.eclipse.swt.graphics.GC;
8 import org.eclipse.swt.graphics.Image;
9 import org.eclipse.swt.graphics.ImageData;
10 import org.eclipse.swt.graphics.ImageLoader;
11 import org.eclipse.swt.widgets.Display;
12
13 public class ScreenCamera {
14
15 Image image;
16
17 public ScreenCamera(Display display) {
18 image = new Image(display, display.getBounds());
19 }
20
21 public void work() throws IOException {
22 new GC(image.getDevice()).copyArea(image, 0, 0);
23 save();
24 }
25
26 /*
27 * 保存文件
28 */
29 void save() throws IOException {
30 File target = new File("screen.png");
31 FileOutputStream out = new FileOutputStream(target);
32 out.write(turnPNGData(image.getImageData()));
33 out.flush();
34 out.close();
35 System.out.println("屏幕图片位置:" + target.getAbsolutePath());
36 }
37
38 /*
39 * 工具方法:将图片数据转化为png格式的文件数据
40 */
41 byte[] turnPNGData(ImageData imageData) {
42 ImageLoader imageLoader = new ImageLoader();
43 imageLoader.data = new ImageData[] { imageData };
44 ByteArrayOutputStream stream = new ByteArrayOutputStream();
45 imageLoader.save(stream, SWT.IMAGE_PNG);
46 return stream.toByteArray();
47 }
48
49 public static void main(String[] args) throws IOException {
50 new ScreenCamera(new Display()).work();
51 }
52 }
53