转: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