Java實現網頁截屏功能(基於phantomJs)

       公司最近有個需求:把用戶第一次的測量身體信息和最近一次測量信息進行對比,而且須要把對比的數據截成圖片能夠發給用戶(須要在不打開網頁的狀況下實時對網頁進行截圖而後保存到服務器上,返回圖片地址),經過網上的一些文章能夠發現有如下幾種實現方式:參考文章https://blog.csdn.net/wanglq0086/article/details/60761614javascript

  • Robot
  • 利用JNI,調用第三方C/C++組件
  • DJNativeSwing組件
  • 利用html2canvas
  • 利用html2image
  • phantomJs

       經過對比效果決定使用phantomJs,PlantomJs是一個基於javascript的webkit內核無頭瀏覽器 也就是沒有顯示界面的瀏覽器,你能夠在基於 webkit 瀏覽器作的事情,它都能作到。PlantomJs提供瞭如 CSS 選擇器、DOM操做、JSON、HTML五、Canvas、SVG 等。PhantomJS 的用處很普遍,如網絡監控、網頁截屏、頁面訪問自動化、無需瀏覽器的 Web 測試等,這裏只用到網頁截屏。PlantomJs能夠經過官網下載http://phantomjs.org/download.html,也能夠經過(只有windows版本):https://pan.baidu.com/s/1EVX1RPX7gY0rGvEI6OHcwg 密碼:brb4 下載;解壓後能夠看到html

 

 負責截圖腳本examples文件夾下rasterize.js以下:java

var page = require('webpage').create(),
    system = require('system'),
    address, output, size;

if (system.args.length < 3 || system.args.length > 5) {
    phantom.exit(1);
} else {
    address = system.args[1];//傳入url地址
    output = system.args[2];//輸出圖片的地址
    page.viewportSize = { width: 800, height: 1800 };//自定義定義寬高
    if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
        size = system.args[3].split('*');
        page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' }
                                           : { format: system.args[3], orientation: 'portrait', margin: '1cm' };
    } else if (system.args.length > 3 && system.args[3].substr(-2) === "px") {
        size = system.args[3].split('*');
        if (size.length === 2) {
            pageWidth = parseInt(size[0], 10);
            pageHeight = parseInt(size[1], 10);
            page.viewportSize = { width: pageWidth, height: pageHeight };
            page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight };
        } else {
            console.log("size:", system.args[3]);
            pageWidth = parseInt(system.args[3], 10);
            pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any
            console.log ("pageHeight:",pageHeight);
            page.viewportSize = { width: pageWidth, height: pageHeight };
        }
    }
    if (system.args.length > 4) {
        page.zoomFactor = system.args[4];
    }
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit(1);
        } else {
            window.setTimeout(function () {
                page.render(output);
                phantom.exit();
            }, 200);
        }
    });
}

address = system.args[1];//傳入url地址

output = system.args[2];//輸出圖片的地址
page.viewportSize = { width: 800, height: 1800 };//自定義定義寬高
 

編寫Java代碼

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Description:根據網頁地址轉換成圖片
 * @Author: admin
 * @CreateDate: 2018年6月22日
 */
public class PhantomTools {
    private static String tempPath = "D:/temp/img";// 圖片保存目錄
    private static String BLANK = " ";
    // 下面內容能夠在配置文件中配置
    private static String binPath = "D:/tooles/phantomjs/phantomjs-2.1.1-windows/bin/phantomjs.exe";// 插件引入地址
    private static String jsPath = "D:/tooles/phantomjs/phantomjs-2.1.1-windows/examples/rasterize.js";// js引入地址

    // 執行cmd命令
    public static String cmd(String imgagePath, String url) {
        return binPath + BLANK + jsPath + BLANK + url + BLANK + imgagePath;
    }
    //關閉命令
    public static void close(Process process, BufferedReader bufferedReader) throws IOException {
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        if (process != null) {
            process.destroy();
            process = null;
        }
    }
    /**
     * @param userId 
     * @param url
     * @throws IOException 
     */
    public static void printUrlScreen2jpg(String url) throws IOException{
        String imgagePath = tempPath+"/"+System.currentTimeMillis()+".png";//圖片路徑
        //Java中使用Runtime和Process類運行外部程序
        Process process = Runtime.getRuntime().exec(cmd(imgagePath,url));
        InputStream inputStream = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String tmp = "";
        while ((tmp = reader.readLine()) != null) {
            close(process,reader);
        }
        System.out.println("success");
    }
    
    public static void main(String[] args) throws IOException {
        String url = "https://www.baidu.com/";//以百度網站首頁爲例
        PhantomTools.printUrlScreen2jpg(url);
    }
}

截圖效果,寬度和高度能夠根據本身的需求在js裏面調整web

相關文章
相關標籤/搜索