HTML文件、网页地址、网页内容 生成图片(Phantomjs)

html2image.jar 支持性特别差!!!!!!!

后面发现了PhantomJS:支持的系统是:windwos、MacOS、Linux

思路:

1.下载exe,http://phantomjs.org/download.html

2.解压到本地磁盘,java调用exe,

3.生成渲染完成的页面效果图png,存放到磁盘

我的路径情况:

exe路径:D:\\c\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe

脚本js路径:D:\\Phantomjs\\execute.js

如图:

上代码:

1.java:

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

/**
 * html-->img
 * TODO 参考https://blog.csdn.net/kaka0930/article/details/68941932
 * @date 2018年7月4日下午4:16:24
 */
public class PhantomjsUtil{
	/**
	 * TODO 调用phantomjs程序,并传入js文件,并通过流拿回需要的数据。
	 * @param httpUrl 网页地址
	 * @param exePath exe绝对路径
	 * @param jsPath js脚本绝对路径
	 * @param imgSavePath 生成图片的存储绝对地址
	 * @return 整个网页html内容
	 * @author yqwang0907
	 * @date 2018年7月4日下午5:03:10
	 */
	public static String getParseredHtml2(String httpUrl,String exePath,String jsPath,String imgSavePath) throws IOException{
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec(exePath + " " + jsPath + " " + httpUrl + " " + imgSavePath);
		InputStream is = p.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuffer sbf = new StringBuffer();
		String tmp = "";
		while ((tmp = br.readLine()) != null){
			sbf.append(tmp);
		}
		System.out.println(sbf);
		return sbf.toString();
	}
	public static void main(String[] args) throws IOException {
		String exePath = "D:\\Phantomjs\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe";
		String jsPath = "D:\\Phantomjs\\execute.js";
		getParseredHtml2("http://www.baidu.com",exePath,jsPath,"D:\\Phantomjs\\"+new Date().getTime()+".png");
	}
} 

excute.js

var page = require('webpage').create(),
	system = require('system'),
	t, httpUrl,imgSavePath;
//写入文件,用来测试。正式版本可以注释掉用来提高速度。
var fs = require("fs");
//读取命令行参数,也就是js文件路径。
if (system.args.length === 1) {
	console.log('Usage: loadspeed.js <some URL>');
	//这行代码很重要。凡是结束必须调用。否则phantomjs不会停止
	phantom.exit();
}
//page.settings.loadImages = false;  //为了提升加载速度,不加载图片
page.settings.resourceTimeout = 10000;//超过10秒放弃加载
//此处是用来设置截图的参数。不截图没啥用
page.viewportSize = {
	width: 3137,
	height: 1275
};
t = Date.now();//看看加载需要多久。
//----参数
httpUrl = system.args[1];
imgSavePath = system.args[2];
//----生成图片,回写html内容
page.open(httpUrl, function(status) {
	if (status !== 'success') {
		console.log('FAIL to load the httpUrl');
	} else {
		t = Date.now() - t;
		page.render(imgSavePath);
		//console.log就是传输回去的内容。
		console.log('Loading time ' + t + ' msec');
		console.log(page.content);
		setTimeout(function(){ phantom.exit(); }, 6000);
	}
	phantom.exit();
});

运行PhantomjsUtil.java中的main()方法得到图片:

===》图片大图:

猜你喜欢

转载自blog.csdn.net/yqwang75457/article/details/80916501