java html转图片
推荐一个好用的图形音频库:https://gitee.com/liuyueyi/quick-media
1.安装phantomjs
windows参考:
phantomjs安装步骤
mac和linux
# 1. 下载
## mac 系统
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-macosx.zip
## linux 系统
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
# 2. 解压
sudo su
tar -jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2
# 如果解压报错,则安装下面的
# yum -y install bzip2
# 3. 安装
## 简单点,移动到bin目录下
cp phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin
# 4. 验证是否ok
phantomjs --version
# 输出版本号,则表示ok
2.添加maven依赖
<!--phantomjs -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
</dependency>
<dependency>
<groupId>com.github.detro</groupId>
<artifactId>ghostdriver</artifactId>
<version>2.1.0</version>
</dependency>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
3测试代码
import org.openqa.selenium.OutputType;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Author: zhiyang.hu
* @Date: 2021/7/29 14:39
* @Description:
*/
public class Html2ImageByJsWrapper {
public static void main(String[] args) throws IOException {
BufferedImage img = null;
String url = "https://phantomjs.org/download.html";
long start = System.currentTimeMillis();
img = Html2ImageByJsWrapper.renderHtml2Image(url);
long end = System.currentTimeMillis();
System.out.println("cost: " + (end - start));
FileOutputStream outputStream1 = new FileOutputStream(new File("C:\Users\wlt\Desktop\img\html2image.png"));
ImageIO.write(img, "png", outputStream1);
}
private static PhantomJSDriver webDriver = getPhantomJs();
private static PhantomJSDriver getPhantomJs() {
//设置必要参数
DesiredCapabilities dcaps = new DesiredCapabilities();
//ssl证书支持
dcaps.setCapability("acceptSslCerts", true);
//截屏支持
dcaps.setCapability("takesScreenshot", true);
//css搜索支持
dcaps.setCapability("cssSelectorsEnabled", true);
//js支持
dcaps.setJavascriptEnabled(true);
//驱动支持(第二参数表明的是你的phantomjs引擎所在的路径,which/whereis phantomjs可以查看)
// fixme 这里写了执行, 可以考虑判断系统是否有安装,并获取对应的路径 or 开放出来指定路径
dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "D:\tools\phantomjs-2.1.1-windows\phantomjs-2.1.1-windows\bin\phantomjs.exe");
//创建无界面浏览器对象
return new PhantomJSDriver(dcaps);
}
public static BufferedImage renderHtml2Image(String url) throws IOException {
webDriver.get(url);
File file = webDriver.getScreenshotAs(OutputType.FILE);
return ImageIO.read(file);
}
}
最后效果: