java 使用PhantomJS把echart保存成图片

该博客展示了使用ECharts生成图片的实现过程。首先给出了展示ECharts的HTML页面代码,包含初始化ECharts实例、处理数据和设置图表选项等。还准备了demo数据,最后介绍了Java使用PhantomJS调用页面生成ECharts图片的代码,包括获取浏览器驱动、执行脚本和获取图片数据等操作。

展示echarts的html页面

<html>
    <meta charset="UTF-8">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
<head>
<script src="http://gssn.fw121.com/js/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/3.8.0/echarts.min.js"></script>
</head>
<body>
    <!-- 因为我需要生成两个图片 所以定义了两个echarts -->
    <!-- 为 ECharts 准备一个具备大小(宽高)的 DOM  -->
    <div id="temEcharts" style="height:400px;width:550px"></div>
    <div id="rhEcharts" style="height:400px;width:550px"></div>
</body>
<script>
    var temEcharts=null;
    var rhEcharts=null;
    $(function() {
        // 基于准备好的dom,初始化echarts实例
        temEcharts = echarts.init(document.getElementById('temEcharts'));
        rhEcharts = echarts.init(document.getElementById('rhEcharts'));
    });
    
    function showImg(surfData){    
        var option ={
                      title : {text : '温度(°C)', left : 'center'},
                      xAxis: {type: 'category', data: []},
                      yAxis: {type: 'value'},
                      series: [{data: [], type: 'line', smooth: true}]
                  }
        if(surfData.length <= 0){
            alert("暂时没有查询到监测数据");
            temEcharts.clear();
            rhEcharts.clear();
            return;
        }else{
            //pre24h需要的数据
            var pre24hdata = echarts.util.map(surfData, function (entry) {
                return entry.pre24h==undefined || entry.pre24h=='99999' ?0:entry.pre24h;
            });
            //温度需要的数据
            var temdata = echarts.util.map(surfData, function (entry) {
                return entry.tem==undefined?0:entry.tem/10;
            });
            //x轴需要的数据
            var xAxisData = echarts.util.map(surfData, function (entry) {
                return formatData(new Date(entry.dataTime), 'MM-dd');
            });
            option.series[0].data=temdata;
            option.xAxis.data=xAxisData;
            temEcharts.setOption(option);
            
            option.series[0].data=pre24hdata;
            option.title.text='降水(mm)';
            option.series[0].type="bar";
            rhEcharts.setOption(option);
        }
    }
    
    function returnEchartImg(echartObj){
        return echartObj.getDataURL();
    }
    
    var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
    var DEFAULT_PATTERN = 'yyyy-MM-dd';

    function formatData(date, pattern) {
        pattern = pattern || DEFAULT_PATTERN;
        return pattern.replace(SIGN_REGEXP, function ($0) {
            switch ($0.charAt(0)) {
                case 'y': return padding(date.getFullYear(), $0.length);
                case 'M': return padding(date.getMonth() + 1, $0.length);
                case 'd': return padding(date.getDate(), $0.length);
                case 'w': return date.getDay() + 1;
                case 'h': return padding(date.getHours(), $0.length);
                case 'm': return padding(date.getMinutes(), $0.length);
                case 's': return padding(date.getSeconds(), $0.length);
            }
        });
    };
    function padding(s, len) {
        var len = len - (s + '').length;
        for (var i = 0; i < len; i++) { s = '0' + s; }
        return s;
    };
    
</script>
</html>

准备需要用到的demo数据(需要将list转成字符串)

String surfData="[
{\"dataTime\":1524758400000,\"dpt\":\"99999\",\"pre24h\":\"999\",\"prs\":\"99999\",\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"99999\",\"tem\":\"227\",\"temMax\":\"99999\",\"temMin\":\"99999\",\"vis\":\"99999\",\"windDAvg10mi\":\"53\",\"windSAvg10mi\":\"99999\"},
{\"dataTime\":1524844800000,\"dpt\":\"99999\",\"pre24h\":\"399\",\"prs\":\"99999\",\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"99999\",\"tem\":\"197\",\"temMax\":\"99999\",\"temMin\":\"99999\",\"vis\":\"99999\",\"windDAvg10mi\":\"66\",\"windSAvg10mi\":\"99999\"},
{\"dataTime\":1524931200000,\"dpt\":\"99999\",\"pre24h\":\"99999\",\"prs\":\"299\",\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"99999\",\"tem\":\"207\",\"temMax\":\"99999\",\"temMin\":\"99999\",\"vis\":\"99999\",\"windDAvg10mi\":\"62\",\"windSAvg10mi\":\"99999\"},
{\"dataTime\":1525017600000,\"dpt\":\"99999\",\"pre24h\":\"99999\",\"prs\":\"99999\",\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"99999\",\"tem\":\"191\",\"temMax\":\"99999\",\"temMin\":\"99999\",\"vis\":\"99999\",\"windDAvg10mi\":\"49\",\"windSAvg10mi\":\"99999\"},
{\"dataTime\":1525190400000,\"dpt\":\"99999\",\"pre24h\":\"959\",\"prs\":\"99999\",\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"\",\"tem\":\"57\",\"temMax\":\"99999\",\"temMin\":\"99999\",\"vis\":\"99999\",\"windDAvg10mi\":\"68\",\"windSAvg10mi\":\"99999\"},
{\"dataTime\":1525276800000,\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"\",\"tem\":\"188\",\"windDAvg10mi\":\"97\",\"windSAvg10mi\":\"99999\"},{\"dataTime\":1525363200000,\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"\",\"tem\":\"216\",\"windDAvg10mi\":\"51\",\"windSAvg10mi\":\"99999\"},
{\"dataTime\":1525449600000,\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"\",\"tem\":\"183\",\"windDAvg10mi\":\"49\",\"windSAvg10mi\":\"99999\"},
{\"dataTime\":1525536000000,\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"\",\"tem\":\"176\",\"windDAvg10mi\":\"91\",\"windSAvg10mi\":\"99999\"},{\"dataTime\":1525622400000,\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"\",\"tem\":\"178\",\"windDAvg10mi\":\"90\",\"windSAvg10mi\":\"99999\"},
{\"dataTime\":1525708800000,\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"\",\"tem\":\"190\",\"windDAvg10mi\":\"94\",\"windSAvg10mi\":\"99999\"},{\"dataTime\":1525795200000,\"rhu\":\"0\",\"station\":\"Y1248\",\"sunlight\":\"\",\"tem\":\"181\",\"windDAvg10mi\":\"73\",\"windSAvg10mi\":\"99999\"}]";
        java使用PhantomJS调用刚才的页面生成echarts图片

        private List<String> saveSurfModelUrlToImg(String surfData) {
        List<String> imageBase64List = new ArrayList<String>();
        PhantomJSDriver driver=getPhantomJSDriver();
        // 让浏览器访问空间主页
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("http://testurl.com/file/upload/saveEchartHtml.html");
        JavascriptExecutor js = (JavascriptExecutor) driver;
        //设置surf数据到页面
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        //展示echarts
        js.executeScript("showImg("+surfData+")");
        //加入一段休眠时间,防止js执行没完成就进行的 读取echart图片数据的功能。
        Thread.sleep(3000); 
        //获取echart图片数据
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        String temTxt=(String) js.executeScript("return returnEchartImg(temEcharts)");
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        String phTxt=(String) js.executeScript("return returnEchartImg(rhEcharts)");
        //imageBase64放到list中
        imageBase64List.add(temTxt.replace("data:image/png;base64,",""));
        imageBase64List.add(phTxt.replace("data:image/png;base64,",""));
//        ImgFileUtils.GenerateImage(temTxt,"d://tem01.png");
//        ImgFileUtils.GenerateImage(phTxt,"d://ph01.png");

        driver.close();
        driver.quit();
        return imageBase64List;
    }

    private PhantomJSDriver getPhantomJSDriver() {
        //设置必要参数
        DesiredCapabilities dcaps = new DesiredCapabilities();
        //ssl证书支持
        dcaps.setCapability("acceptSslCerts", true);
        //截屏支持
        dcaps.setCapability("takesScreenshot", true);
        //css搜索支持
        dcaps.setCapability("cssSelectorsEnabled", true);
        //js支持
        dcaps.setJavascriptEnabled(true);
        //驱动支持
        String osname = System.getProperties().getProperty("os.name");
        if (osname.equals("Linux")) {//判断系统的环境win or Linux
            dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,"/usr/bin/phantomjs");
        } else {
            dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,"D:\\phantomjs-2.1.1\\bin\\phantomjs.exe");
        }
        //创建无界面浏览器对象
        PhantomJSDriver driver = new PhantomJSDriver(dcaps);
        return  driver;
    }
 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lozhyf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值