本帖最后由 wushaominkk 于 2019-11-18 20:19 编辑
[Java] 纯文本查看 复制代码 //网页快照工具类
package com.snap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
public class SnapUtills {
static String phantomjsPath;
static {
// 判断是什么环境
String systemType = System.getProperties().getProperty("os.name");
if (systemType != null && systemType.toLowerCase().indexOf("windows") > -1) {
phantomjsPath = System.getProperty("user.dir") + "\\phantomjs\\phantomjs-2.1.1-windows";
} else {
phantomjsPath = System.getProperty("user.dir") + "\\phantomjs\\phantomjs-2.1.1-linux-x86_64";
}
}
/**
* 生成网页缩略图
*/
public static String snapUrl(String url, String savePath) throws Exception {
String cmd = phantomjsPath + "/bin/phantomjs ";
String jspath = phantomjsPath + "/examples/rasterize.js";
// 执行命令,超时60秒退出
execCMD(cmd + jspath + " " + url + " " + savePath, 60);
return savePath;
}
/**
* 命令执行(超过多少秒退出)
*
* @Param cmd 命令
* @param timeout 秒
*/
private static String execCMD(String cmd, int timeout) throws Exception {
Process process = null;
StringBuilder sbStd = new StringBuilder();
StringBuilder sbErr = new StringBuilder();
long start = System.currentTimeMillis() / 1000;
try {
process = Runtime.getRuntime().exec(cmd);
BufferedReader brStd = new BufferedReader(new InputStreamReader(
process.getInputStream()));
BufferedReader brErr = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
String line = null;
while (true) {
if (brStd.ready()) {
line = brStd.readLine();
sbStd.append(line + "\n");
continue;
}
if (brErr.ready()) {
line = brErr.readLine();
sbErr.append(line + "\n");
continue;
}
if (process != null) {
try {
process.exitValue();
break;
} catch (IllegalThreadStateException e) {
}
}
if (System.currentTimeMillis() / 1000 - start > timeout) {
sbErr.append("\ntimeout");
break;
}
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
}
}
} catch (IOException e) {
throw e;
} finally {
if (process != null) {
process.destroy();
}
}
if (sbErr.length() > 0) {
throw new Exception(sbErr.toString());
} else {
return sbStd.toString();
}
}
}
//测试
package com.snap;
public class Test {
public static void main(String[] args) throws Exception {
String savePath = System.getProperty("user.dir") + "\\snap-image\\" + System.currentTimeMillis() + ".jpg";
String snapUrl = SnapUtills.snapUrl("https://www.baidu.com", savePath);
System.out.println("生成网页快照图片的路径:" + snapUrl);
}
}
具体项目代码:https://download.csdn.net/download/qq_24101357/11970303
|