Java & PhantomJs 實現html輸出圖片

Java & PhantomJs 實現html輸出圖片

藉助phantomJs來實現將html網頁輸出爲圖片css

I. 背景

如何在小程序裏面生成一張圖,分享到朋友圈呢?目前前端貌似沒有太好的解決方法,因此只能猥瑣的由後端來支持掉,那麼能夠怎麼玩?html

生成圖片比較簡單

簡單的場景,能夠直接用jdk來支持掉,通常來說也沒有太複雜的邏輯前端

以前寫過一個圖片合成的邏輯,利用awt實現: 圖片合成java

通用、複雜的模板

簡單的能夠直接支持,但複雜一點的,讓後端來支持,無疑比較噁心,在github上也搜索了一些渲染html的開源庫,不知道是姿式不對仍是咋的,沒有太滿意的結果linux

如今對複雜的模板,要怎麼支持呢?git

也就是本篇的指南,利用phantomjs來實現html的渲染,支持生成pdf,生成圖片,解析dom都ok,接下來則演示下如何結合 phantomjs 搭建一個網頁渲染成圖片的服務github

II. 前提準備

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 配置添加依賴web

<!--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渲染圖片的邏輯以下macos

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

public class Base64Util {

    public static String encode(BufferedImage bufferedImage, String imgType) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, imgType, outputStream);
        return encode(outputStream);
    }

    public static String encode(ByteArrayOutputStream outputStream) {
        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }

}

@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(Base64Util.encode(img, "png"));
}

生成的圖片就不貼了,有興趣的能夠直接到個人網站上實測小程序

III. 網絡實測

在阿里雲服務器上部署了一個簡單的web應用,支持了html輸出圖片的功能;因爲買的是乞丐版,用的前端模板又比較酷炫,因此打開較慢....

友情連接 : https://zbang.online/web/html/toimg

操做演示:

html輸出image

IV. 項目

項目地址:

  • quick-media
  • QuickMedia是一個專一圖文,音視頻,二維碼處理等面向多媒體服務的開源項目

掃描關注,提供更多有趣的編碼知識

公衆號

相關文章
相關標籤/搜索