有時候,我們需要用代碼來網頁,其實要實現這個功能,無非就是要麼實現一個模擬瀏覽器,要麼調用系統瀏覽器,唯有此而發而已。這裡還是用的最常見的第二種,第一種難度很大。在網上找了一個庫,很好用,記錄下來,僅供有需要的同學參考。
:http://code.google.com/p/greenvm/downloads/detail?name=Screenshot.7z&can=2&q=
Screenshot就是這樣的一個程式,這是一個以DJNativeSwing於系統後台呼叫瀏覽器,產生指定網頁地址的樣本。
部分核心代碼如下:
public Main(final String url, final int maxWidth, final int maxHeight) {
super(new BorderLayout());
JPanel webBrowserPanel = new JPanel(new BorderLayout());
final String fileName = System.currentTimeMillis() + ".jpg";
final JWebBrowser webBrowser = new JWebBrowser(null);
webBrowser.setBarsVisible(false);
webBrowser.navigate(url);
webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
add(webBrowserPanel, BorderLayout.CENTER);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4));
webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
// 監聽載入進度
public void loadingProgressChanged(WebBrowserEvent e) {
// 當載入完畢時
if (e.getWebBrowser().getLoadingProgress() == 100) {
String result = (String) webBrowser
.executeJavascriptWithResult(jsDimension.toString());
int index = result == null ? -1 : result.indexOf(":");
NativeComponent nativeComponent = webBrowser
.getNativeComponent();
Dimension originalSize = nativeComponent.getSize();
Dimension imageSize = new Dimension(Integer.parseInt(result
.substring(0, index)), Integer.parseInt(result
.substring(index + 1)));
imageSize.width = Math.max(originalSize.width,
imageSize.width + 50);
imageSize.height = Math.max(originalSize.height,
imageSize.height + 50);
nativeComponent.setSize(imageSize);
BufferedImage image = new BufferedImage(imageSize.width,
imageSize.height, BufferedImage.TYPE_INT_RGB);
nativeComponent.paintComponent(image);
nativeComponent.setSize(originalSize);
// 當網頁超出目標大小時
if (imageSize.width > maxWidth
|| imageSize.height > maxHeight) {
//部分圖形
image = image.getSubimage(0, 0, maxWidth, maxHeight);
/*此部分為使用縮圖
int width = image.getWidth(), height = image
.getHeight();
AffineTransform tx = new AffineTransform();
tx.scale((double) maxWidth / width, (double) maxHeight
/ height);
AffineTransformOp op = new AffineTransformOp(tx,
AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
//縮小
image = op.filter(image, null);*/
}
try {
// 輸出映像
ImageIO.write(image, "jpg", new File(fileName));
} catch (IOException ex) {
ex.printStackTrace();
}
// 退出操作
System.exit(0);
}
}
}
);
add(panel, BorderLayout.SOUTH);
}
轉載註明:http://www.zhurouyoudu.com/index.php/archives/374/