java網頁快照-網頁轉存為圖片實現代碼

來源:互聯網
上載者:User
 代碼如下 複製代碼

 運行環境:jdk1.6以上

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 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 Main extends JPanel {
 /**
  *
  */
 private static final long serialVersionUID = 1L;

 // 行分隔字元
 final static public String LS = System.getProperty("line.separator", "n");

 // 檔案分割符
 final static public 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 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);

 }

 public static void main(String[] args) {
  NativeInterface.open();
  SwingUtilities.invokeLater(new Runnable() {
   public void run() {
    // SWT組件轉Swing組件,不初始化父表單將無法啟動webBrowser
    JFrame frame = new JFrame("以DJ組件儲存指定網頁截圖");
    // 載入google,最大儲存為640x480的截圖
    frame.getContentPane().add(
      new Main(http://yijianfengvip.blog.163.com/, 640, 480),
      BorderLayout.CENTER);
    frame.setSize(800, 600);
    // 僅初始化,但不顯示
    frame.invalidate();
    frame.pack();
    frame.setVisible(false);
   }
  });
  NativeInterface.runEventPump();
 }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.