动态生成图片"/>
利用phantomjs动态生成图片
好记忆不如烂笔头,能记下点东西,就记下点,有时间拿出来看看,也会发觉不一样的感受。
目录
一、问题
二、可行方案
三具体实施:
1.phantomjs 安装运行
2.查找echarts图片
3.生成图片
4.echarts-convert.js
一、问题
为什么需要动态生成图片呐,主要的用途就在于根据参数的不同,生成不同图片,进而生成个性化,定制化的报告。
那么该如何实现图片的动态生成呐 ?
二、可行方案
phantomjs + echarts 的方式来实现。
三具体实施:
1.phantomjs 安装运行
下载地址:
官网下载地址:.html
我这里选择的版本是 phantomjs-2.1.1-linux-x86_64.tar.bz2
windows版本的安装,这里再多言
安装步骤
解压安装
tar -jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2
mv phantomjs-2.1.1-linux-x86_64.tar.bz2 /opt/phantomjs
配置环境变量
vim /etc/profile
在 profile 文件末端加上如下配置
PHANTOMJS_HOME=/opt/phantomjs
export PATH=$PATH:$PHANTOMJS_HOME/bin
激活环境变量
source /etc/profile
运行命令 phantomjs 成功安装,如果有phantomjs> 那证明安装成功
可能遇到的问题:
报错如下:
phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
解决方案:
apt-get install libfontconfig1
切记:在有网络的条件下执行,如果是没有网络,那么安装会因为缺包而很麻烦.
2.查找echarts图片
地址: .html
查找满足你需要的图形,然后拷贝里面的json内容,并将内容放置在 temp.json文件中去
3.生成图片
调用phantomjs动态生成相应的图片。
命令格式如下:phantomjs的安装地址 转换的js 指定输入 输入对象 指定输出 输出对象
例如:phantomjs echarts-convert.js -infile tmp.json -outfile tmp.png
4.echarts-convert.js
(function () {
var system = require('system');
var fs = require('fs');
var config = {// define the location of js filesJQUERY: 'jquery-3.2.1.min.js',//ESL: 'esl.js',ECHARTS: 'echarts.min.js',// default container width and heightDEFAULT_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 opitonsif (inputOption != 'undefined') {// parse the optionsloadScript('options', inputOption);// disable the animationoptions.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 chartvar myChart = echarts.init(container[0]);myChart.setOption(options);// load imagesloadImages();return myChart.getDataURL();};// parse the paramspage.open("about:blank", function (status) {// inject the dependency jspage.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 chartvar base64 = page.evaluate(createChart, params.options, width, height,config);fs.write("base64.txt",base64);// define the clip-rectanglepage.clipRect = {top: 0,left: 0,width: width,height: height};// render the imagepage.render(params.outfile);console.log('render complete:' + params.outfile);// exitphantom.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);
}());
更多推荐
利用phantomjs动态生成图片
发布评论