28 Star 120 Fork 50

一灰灰Blog / quick-media

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
html2img.md 3.02 KB
一键复制 编辑 原始数据 按行查看 历史
yihui 提交于 2017-12-01 19:08 . #22 利用phantomjs 实现html转图片

Java & PhantomJs 实现html输出图片

借助phantomJs来实现将html网页输出为图片

前提准备

1. phantom.js 安装

# 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

## windows 系统
## 就不要玩了,没啥意思


# 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. java依赖配置

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>

开动

主要调用phantomjs来实现html渲染图片的逻辑如下

public class Html2ImageByJsWrapper {

    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, "/usr/local/bin/phantomjs");
        //创建无界面浏览器对象
        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);
    }

}

测试case

@Test
public void testRender() throws IOException {
    BufferedImage img = null;
    for (int i = 0; i < 20; ++i) {
        String url = "https://my.oschina.net/u/566591/blog/1580020";
        long start = System.currentTimeMillis();
        img = Html2ImageByJsWrapper.renderHtml2Image(url);
        long end = System.currentTimeMillis();
        System.out.println("cost:  " + (end - start));
    }

    System.out.println(DomUtil.toDomSrc(Base64Util.encode(img, "png"), MediaType.ImagePng));

}
Java
1
https://gitee.com/liuyueyi/quick-media.git
git@gitee.com:liuyueyi/quick-media.git
liuyueyi
quick-media
quick-media
master

搜索帮助