Java PhantomJS+ECharts Windows 生成图片

Java PhantomJS+ECharts Windows 生成图片

菜鸡程序员小童准备用Java生成图片啦,主要是为了生成图表哦

简单的效果图
在这里插入图片描述
开始准备下手吧~

下载安装PhantomJS

下载

选择Windows版本,我选择的是2.1.1版本

https://phantomjs.org/download.html

部署环境

PHANTOM_JS_HOME=D:\phantomjs\phantomjs-2.1.1-windows
Path:%PHANTOM_JS_HOME%\bin

验证

出现版本号即成功

phantomjs --version

准备脚本

需要用到以下三个脚本,把三个脚本放入同一个目录下

jquery-3.4.1.min.js

下载路径,可更换其它版本

https://www.bootcdn.cn/

echarts.min.js

下载路径

https://www.bootcdn.cn/

echarts-convert.js

(function () {
var system = require('system');
var fs = require('fs');
var config = {
    // define the location of js files
    JQUERY: 'jquery-3.4.1.min.js',
    //ESL: 'esl.js',
    ECHARTS: 'echarts.min.js',
    // default container width and height
    DEFAULT_WIDTH: '600',
    DEFAULT_HEIGHT: '700'
}, parseParams, render, pick, usage;

usage = function () {
    console.log("\nUsage: phantomjs echarts-convert.js -options options -outfile filename -width width -height height"
        + "OR"
        + "Usage: phantomjs echarts-convert.js -infile URL -outfile filename -width width -height height\n");
};

pick = function () {
    var args = arguments, i, arg, length = args.length;
    for (i = 0; i < length; i += 1) {
        arg = args[i];
        if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') {
            return arg;
        }
    }
};

parseParams = function () {
    var map = {}, i, key;
    if (system.args.length < 2) {
        usage();
        phantom.exit();
    }
    for (i = 0; i < system.args.length; i += 1) {
        if (system.args[i].charAt(0) === '-') {
            key = system.args[i].substr(1, i.length);
            if (key === 'infile') {
                // get string from file
                // force translate the key from infile to options.
                key = 'options';
                try {
                    map[key] = fs.read(system.args[i + 1]).replace(/^\s+/, '');
                } catch (e) {
                    console.log('Error: cannot find file, ' + system.args[i + 1]);
                    phantom.exit();
                }
            } else {
                map[key] = system.args[i + 1].replace(/^\s+/, '');
            }
        }
    }
    return map;
};

render = function (params) {
    var page = require('webpage').create(), createChart;

    var bodyMale = config.SVG_MALE;
    page.onConsoleMessage = function (msg) {
        console.log(msg);
    };

    page.onAlert = function (msg) {
        console.log(msg);
    };

    createChart = function (inputOption, width, height,config) {
        var counter = 0;
        function decrementImgCounter() {
            counter -= 1;
            if (counter < 1) {
                console.log(messages.imagesLoaded);
            }
        }

        function loadScript(varStr, codeStr) {
            var script = $('<script>').attr('type', 'text/javascript');
            script.html('var ' + varStr + ' = ' + codeStr);
            document.getElementsByTagName("head")[0].appendChild(script[0]);
            if (window[varStr] !== undefined) {
                console.log('Echarts.' + varStr + ' has been parsed');
            }
        }

        function loadImages() {
            var images = $('image'), i, img;
            if (images.length > 0) {
                counter = images.length;
                for (i = 0; i < images.length; i += 1) {
                    img = new Image();
                    img.onload = img.onerror = decrementImgCounter;
                    img.src = images[i].getAttribute('href');
                }
            } else {
                console.log('The images have been loaded');
            }
        }
        // load opitons
        if (inputOption != 'undefined') {
            // parse the options
            loadScript('options', inputOption);
            // disable the animation
            options.animation = false;
        }

        // we render the image, so we need set background to white.
        $(document.body).css('backgroundColor', 'white');
        var container = $("<div>").appendTo(document.body);
        container.attr('id', 'container');
        container.css({
            width: width,
            height: height
        });
        // render the chart
        var myChart = echarts.init(container[0]);
        myChart.setOption(options);
        // load images
        loadImages();
        return myChart.getDataURL();
    };

    // parse the params
    page.open("about:blank", function (status) {
        // inject the dependency js
        page.injectJs(config.ESL);
        page.injectJs(config.JQUERY);
        page.injectJs(config.ECHARTS);


        var width = pick(params.width, config.DEFAULT_WIDTH);
        var height = pick(params.height, config.DEFAULT_HEIGHT);

        // create the chart
        var base64 = page.evaluate(createChart, params.options, width, height,config);
        fs.write("base64.txt",base64);
        // define the clip-rectangle
        page.clipRect = {
            top: 0,
            left: 0,
            width: width,

            height: height
        };
        // render the image
        page.render(params.outfile);
        console.log('render complete:' + params.outfile);
        // exit
        phantom.exit();
    });
};
// get the args
var params = parseParams();

// validate the params
if (params.options === undefined || params.options.length === 0) {
    console.log("ERROR: No options or infile found.");
    usage();
    phantom.exit();
}
// set the default out file
if (params.outfile === undefined) {
    var tmpDir = fs.workingDirectory + '/tmp';
    // exists tmpDir and is it writable?
    if (!fs.exists(tmpDir)) {
        try {
            fs.makeDirectory(tmpDir);
        } catch (e) {
            console.log('ERROR: Cannot make tmp directory');
        }
    }
    params.outfile = tmpDir + "/" + new Date().getTime() + ".png";
}

// render the image
render(params);
}());

准备options

我的理解是这是一个包含生成图表的参数JSON(如果理解错了,请指出哦)

{
	"title": {
		"text": "性别图",
		"subtext": "男女比例",
		"x": "CENTER"
	},
	"toolbox": {
		"feature": {
			"saveAsImage": {
				"show": true
			}
		}
	},
	"tooltip": {
		"show": true
	},
	"legend": {
		"data": ["男", "女", "其它"]
	},
	"series": [{
		"name": "性别",
		"type": "pie",
		"radius": "80 %",
		"center": ["50%", "60%"],
		"data": [{
			"value": 265,
			"name": "男"
		}, {
			"value": 320,
			"name": "女"
		}, {
			"value": 113,
			"name": "其它"
		}]
	}]
}

执行cmd命令

phantomjs echarts-convert.js路径 -infile options的json路径 -outfile 输出图片路径

phantomjs F:\js\echarts-convert.js -infile F:\js\options.json -outfile F:\js\out.png

这种方式即可生成图表
若需要java批量执行,或者多线程
即可参考下面的java调用cmd命令

Java多线程调用

package com.cl.marketing;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class EchartsTest {

    private static final String JSpath = "F:\\js\\echarts-convert.js";

    public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        int x = 100;
        int nThreads = Runtime.getRuntime().availableProcessors() * 2;
        List<Future<Boolean>> futures = new ArrayList<>();
        ExecutorService exec = Executors.newFixedThreadPool(nThreads);
        while (x > 0) {
            EchartsCall task = new EchartsCall();
            Future<Boolean> future = exec.submit(task);
            futures.add(future);
            x--;
        }
        for (Future<Boolean> f : futures) {
            try {
                f.get();
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.println("time:" + (t2 - t1));
    }
    
    public static String generateEChart(String options) {
        String dataPath = writeFile(options);
        String fileName = UUID.randomUUID().toString() + ".png";
        String path = "F:\\js\\data\\" + fileName;
        try {
            File file = new File(path); // 文件路径
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            String cmd = "phantomjs " + JSpath + " -infile " + dataPath + " -outfile " + path;// 生成命令行
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
            input.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return path;
    }

    public static String writeFile(String options) {
        String dataPath = "F:\\js\\data\\" + UUID.randomUUID().toString().substring(0, 8) + ".json";
        try {
            /* option写入文本文件 用于执行命令 */
            File writename = new File(dataPath);
            if (!writename.exists()) {
                File dir = new File(writename.getParent());
                dir.mkdirs();
                writename.createNewFile(); //
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(options);
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 最后关闭文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataPath;
    }
    public static class EchartsCall implements Callable<Boolean> {


        @Override
        public Boolean call() throws Exception {
            String options = "{\n" + 
                    "    \"title\": {\n" + 
                    "        \"text\": \"性别图\",\n" + 
                    "        \"subtext\": \"男女比例\",\n" + 
                    "        \"x\": \"CENTER\"\n" + 
                    "    },\n" + 
                    "    \"toolbox\": {\n" + 
                    "        \"feature\": {\n" + 
                    "            \"saveAsImage\": {\n" + 
                    "                \"show\": true\n" + 
                    "            }\n" + 
                    "        }\n" + 
                    "    },\n" + 
                    "    \"tooltip\": {\n" + 
                    "        \"show\": true\n" + 
                    "    },\n" + 
                    "    \"legend\": {\n" + 
                    "        \"data\": [\"男\", \"女\", \"其它\"]\n" + 
                    "    },\n" + 
                    "    \"series\": [{\n" + 
                    "        \"name\": \"性别\",\n" + 
                    "        \"type\": \"pie\",\n" + 
                    "        \"radius\": \"80 %\",\n" + 
                    "        \"center\": [\"50%\", \"60%\"],\n" + 
                    "        \"data\": [{\n" + 
                    "            \"value\": 265,\n" + 
                    "            \"name\": \"男\"\n" + 
                    "        }, {\n" + 
                    "            \"value\": 320,\n" + 
                    "            \"name\": \"女\"\n" + 
                    "        }, {\n" + 
                    "            \"value\": 113,\n" + 
                    "            \"name\": \"其它\"\n" + 
                    "        }]\n" + 
                    "    }]\n" + 
                    "}";
            generateEChart(options);
            return true;
        }
        public EchartsCall() {
        }
    }
}

参考 感谢
大佬1号.
大佬2号.

发布了9 篇原创文章 · 获赞 11 · 访问量 945

猜你喜欢

转载自blog.csdn.net/superice_/article/details/102708950