Java呼叫phantomJs實現網頁截圖功能
轉:http://www.cnblogs.com/han108/p/9216583.html 這篇文章寫得很好, 我自己補充了一下,內含安裝包比較全
1.首先介紹一下環境 java環境不用多說,jdk1.7 + phantomJs-2.1.1
2.安裝包資源:https://download.csdn.net/download/kai402458953/10856573
selenium-java-2.53.0最全jar,phantomjs.zip 需要一積分,自行下載哈
phantomjs.zip 解壓即可:
我的安裝目錄是:
3.建立java專案即可,專案結構
4.直接上原始碼:
package com.js.jsutil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* @Description:根據網頁地址轉換成圖片
* @Author: admin
* @CreateDate: 2018年12月19日
*/
public class GetImgByPjs {
private static String tempPath = "F:/images/img";// 圖片儲存目錄
private static String BLANK = " ";
// 下面內容可以在配置檔案中配置
private static String binPath = "D:/phantomjs/phantomjs-2.1.1-windows/bin/phantomjs.exe";// 外掛引入地址
private static String jsPath = "D:/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/";//以百度網站首頁為例
GetImgByPjs.printUrlScreen2jpg(url);
}
}
本人的phantomjs截圖專案原始碼:https://download.csdn.net/download/kai402458953/10861748