import java.util.Date;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class WebSnap {
public static final int PNG = SWT.IMAGE_PNG;
public static final int BMP = SWT.IMAGE_BMP;
public static final int JPG = SWT.IMAGE_JPEG;
public static final int GIF = SWT.IMAGE_GIF;
public static final int TIFF = SWT.IMAGE_TIFF;
private Display display;
private Shell shell;
private Browser browser;
/**
* 截圖寬度
*/
private int width;
/**
* 截圖高度
*/
private int height;
/**
* @param width
* 截圖寬度
* @param height
* 截圖高度
* @param url
* 目標網址URL
*/
public WebSnap(int width, int height, String url) {
this.width = width;
this.height = height;
this.display = new Display();
this.shell = new Shell(this.display);
this.shell.setLayout(new FillLayout());
this.shell.setSize(width, height);
this.shell.setText("Web Snap");
this.browser = new Browser(this.shell, SWT.NONE);
this.browser.setSize(width, height);
this.browser.setUrl(url);
}
/**
* @param file
* 圖片存檔路徑
* @param swtImageType
* 圖片存檔類型
*/
private void snap(String file, int swtImageType) {
Image data = new Image(this.display, this.width, this.height);
this.browser.print(new GC(data));
ImageLoader il = new ImageLoader();
il.data = new ImageData[] { data.getImageData() };
il.save(file, swtImageType);
data.dispose();
}
/**
* @param file
* 圖片存檔路徑
* @param swtImageType
* 圖片存檔類型
* @param sleepTick
* 延遲時間
*/
public void asynSnap(final String file, final int type, final long sleepTick) {
new Thread() {
public void run() {
try {
Thread.sleep(sleepTick);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebSnap.this.display.asyncExec(new Runnable() {
public void run() {
WebSnap.this.snap(file, type);
WebSnap.this.shell.dispose();
}
});
};
}.start();
this.waitForDispose();
}
private void waitForDispose() {
while (!this.shell.isDisposed()) {
if (!this.display.readAndDispatch()) {
this.display.sleep();
}
}
this.display.dispose();
}
public static void main(String[] args) {
int width = 1024, height = 768;
String url = "http://tw.yahoo.com";
String file = String.format("w%d.png", new Date().getTime());
WebSnap ws = new WebSnap(width, height, url);
ws.asynSnap(file, WebSnap.PNG, 18000);
}
}