Java爱好者 - 专注于Java技术Java爱好者 - 专注于Java技术

如何Java实现网页截图技术

1、最直接的方式——使用Robot

 

方法详解:该方法利用Robat提供的强大桌面操作能力,硬性调用浏览器打开指定网页,并将网页信息保存到本地。

 

优势:简单易用,不需要任何第三方插件。

 

缺点:不能同时处理大量数据,技术含量过低,属于应急型技巧(不推荐)。

 

实现方法:使用如下代码即可。

package cc.javar.util;
import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.imageio.ImageIO;
public class CutPicture {
    public  void main() throws MalformedURLException,
            IOException, URISyntaxException, AWTException {
        // 此方法仅适用于JdK1.6及以上版本
        Desktop.getDesktop().browse(
                new URL("http://www.baidu.com").toURI());
        Robot robot = new Robot();
        robot.delay(10000);
        Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
        int width = (int) d.getWidth();
        int height = (int) d.getHeight();
        // 最大化浏览器
        robot.keyRelease(KeyEvent.VK_F11);
        robot.delay(2000);
        Image image = robot.createScreenCapture(new Rectangle(0, 0, width,
                height));
        BufferedImage bi = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);
        // 保存图片
        ImageIO.write(bi, "jpg", new File("d:/google"+System.currentTimeMillis()+".jpg"));
    }
}

2.比较好用的组建,正在调试,需要JWebBrowser 组件。

package cc.javar.util;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils.IO;
import chrriis.dj.nativeswing.swtimpl.NativeComponent;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserAdapter;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserEvent;
public class ScreenUtils extends JPanel {
    public static final long serialVersionUID = 1L;
    // 行分隔符  
    public static final String LS = System.getProperty("line.separator", "/n");
    // 文件分割符  
    public static final String FS = System.getProperty("file.separator", "//");
    //以javascript脚本获得网页全屏后大小  
    final static StringBuffer jsDimension;
    static {
        jsDimension = new StringBuffer();
        jsDimension.append("var width = 0;").append(LS);
        jsDimension.append("var height = 0;").append(LS);
        jsDimension.append("if(document.documentElement) {").append(LS);
        jsDimension.append("width = Math.max(width, document.documentElement.scrollWidth);").append(LS);
        jsDimension.append("height = Math.max(height, document.documentElement.scrollHeight);").append(LS);
        jsDimension.append("}").append(LS);
        jsDimension.append("if(self.innerWidth) {").append(LS);
        jsDimension.append("width = Math.max(width, self.innerWidth);").append(LS);
        jsDimension.append("height = Math.max(height, self.innerHeight);").append(LS);
        jsDimension.append("}").append(LS);
        jsDimension.append("if(document.body.scrollWidth) {").append(LS);
        jsDimension.append("width = Math.max(width, document.body.scrollWidth);").append(LS);
        jsDimension.append("height = Math.max(height, document.body.scrollHeight);").append(LS);
        jsDimension.append("}").append(LS);
        jsDimension.append("return width + ':' + height;");
    }
    public ScreenUtils(final String fileName, final String url, final int maxWidth, final int maxHeight) {
        super(new BorderLayout());
        JPanel webBrowserPanel = new JPanel(new BorderLayout());
        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);
                    try {
                        // 输出图像  
                        ImageIO.write(image, "jpg", new File(fileName));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    // 退出操作  
                    System.exit(0);
                }
            }
        }
        );
        add(panel, BorderLayout.SOUTH);
    }
    public static void Screen(final String fileName,final String url){
        NativeInterface.open();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // SWT组件转Swing组件,不初始化父窗体将无法启动webBrowser  
                JFrame frame = new JFrame("以DJ组件保存指定网页截图");
                // 加载指定页面,最大保存为640x480的截图  
                frame.getContentPane().add(new ScreenUtils(fileName, url, 1024, 768),BorderLayout.CENTER);
                frame.setSize(1024, 768);
                // 仅初始化,但不显示  
                frame.invalidate();
                frame.pack();
                frame.setVisible(false);
            }
        });
        NativeInterface.runEventPump();
   }
}

需要的JAR包

本原创文章未经允许不得转载 | 当前页面:Java爱好者 - 专注于Java技术 » 如何Java实现网页截图技术

评论

文章评论已关闭!