
正文
Java实现网页截屏功能(基于phantomJs)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
公司最近有个需求:把用户第一次的测量身体信息和最近一次测量信息进行对比,并且需要把对比的数据截成图片可以发给用户(需要在不打开网页的情况下实时对网页进行截图然后保存到服务器上,返回图片地址),通过网上的一些文章可以发现有以下几种实现方式:参考文章https://blog.csdn.net/wanglq0086/article/details/60761614
- Robot
- 利用JNI,调用第三方C/C++组件
- DJNativeSwing组件
- 利用html2canvas
- 利用html2image
- phantomJs
通过对比效果决定使用phantomJs,PlantomJs是一个基于javascript的webkit内核无头浏览器 也就是没有显示界面的浏览器,你可以在基于 webkit 浏览器做的事情,它都能做到。PlantomJs提供了如 CSS 选择器、DOM操作、JSON、HTML5、Canvas、SVG 等。PhantomJS 的用处很广泛,如网络监控、网页截屏、页面访问自动化、无需浏览器的 Web 测试等,这里只用到网页截屏。PlantomJs可以通过官网下载http://phantomjs.org/download.html,也可以通过(只有windows版本):https://pan.baidu.com/s/1EVX1RPX7gY0rGvEI6OHcwg 密码:brb4 下载;解压后可以看到

负责截图脚本examples文件夹下rasterize.js如下:
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);
}
}
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里面调整







