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);
}
}
最後效果: