开发中遇到的任务需求是,将html5中的内容替换为实时数据后截图,截图的长宽要求是750*3327,将截图的资源路径返回给前端展示及下载
我的java代码:
// url就是图片的地址,imgPath是图片保存的路径
public static String ScreenShot(String url, String imgPath) throws Exception {
// phantomjs所在的路径
String execPath = "/usr/local/phantomjs-2.1.1-linux-x86_64/bin/phantomjs";
// 自己写的js代码所在的位置
String jsPath = "/home/java/project/inews/inews_report_read/htmlPath/HotScreenshot.js";
if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
execPath = "D:\\测试报告\\bin\\phantomjs.exe";
}
// 使用runtime去执行屏幕截图
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(execPath + " " + jsPath + " " + url + " " + imgPath);
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
// 成功后返回的图片位置
String result = bufferedReader.readLine();
System.out.println(result);
return result;
}
我的js文件代码:
var page = require('webpage').create();
system = require('system');
phantom.cutputEncoding = 'utf-8';
// 设置图片的宽度及高度
page.viewportSize = {width: 750, height: 3327};
page.clipRect = {
width: 750,
height: 3327
};
// 设置截图的比列
page.zoomFactor = 2;
var url = system.args[1];
var imgPath = system.args[2];
page.open(url, function (status) {
var result = {};
if (status === "success") {
setTimeout(function () {
// page.evaluate(function() {
page.render(imgPath);
result["status"] = 1;
result["file"] = imgPath;
console.log(JSON.stringify(result));
phantom.exit();
// });
}, 3000);
// 3000是睡眠时间,要等页面加载完所以需要睡眠
} else {
result["status"] = -1;
console.log(JSON.stringify(result));
phantom.exit();
}
});
});
效果图:
截图的大小及比列需要自己在js文件中调整
遇到的问题及解决逻辑:
首先这个phantomjs是只能根据url来截图的,不能直接根据html截图,所以我就把这个html文件修改实时数据之后放到linux中的静态资源文件夹,并拿到html的url地址,就可以进行截图了