纯后台生成echarts图片-phantomjs-2.1.1

2023-10-29 18:48

本文主要是介绍纯后台生成echarts图片-phantomjs-2.1.1,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

问题场景

后端需要定时发邮件,邮件正文带图片,图片要求每次即时生成。

开发环境

idea+Java8+springboot2
echart-convert.js
phantomjs-2.1.1与字体

分析

phantomjs可以模拟浏览器执行js请求ajax等效果,俗称无头浏览器,可以用于客户端渲染。

步骤

  1. 下载上述资源,放入工程里,待调用。
  2. 安装phantomjs-2.1.1及微软雅黑字体[图表中文乱码-服务器可能需要安装字体]

 字体:- yum install -y mkfontscale- yum install -y fontconfig- mkdir /usr/share/fonts/chinese- cp msyh.ttf /usr/share/fonts/chinese- mkfontscale- mkfontdir- fc-cache -fv# 查看是否安装成功- fc-list

 phantomjs-2.1.1- yum install -y bzip2# just do it- yum install -y fontconfig freetype libfreetype.so.6- tar -jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2 -C /usr/local/# 创建软链接- ln -s /usr/local/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs# 验证安装是否成功- phantomjs --version
  1. 引入maven依赖
<dependency><groupId>com.github.abel533</groupId><artifactId>ECharts</artifactId><version>2.2.7</version>
</dependency>
  1. 后台组织好echart生成图片的option
  2. 调用下面的代码
import com.github.abel533.echarts.Grid;
import com.github.abel533.echarts.Label;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.TextStyle;
import com.github.abel533.echarts.style.itemstyle.Normal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import com.github.abel533.echarts.axis.AxisLabel;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Magic;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** 〈〉** @author yangyouxing* @create 2019-12-18* @since 1.0.0*/
@Slf4j
@Service
public class ImageServiceImpl {/*** 调用phantomjs产生图片* @param options       echarts的options* @param imgName       图片名称路径* @param width         1680* @param height        500* @return*/public String createEchartImage(String options, String imgName, Long width, Long height) {String path = "";BufferedReader input = null;String cmd = "";try {// 工具类自己搞if (OSUtil.isLinux()) {path = "/usr/local/download/" + imgName;} else {path = ResourceUtils.getURL("classpath:download").getPath() + File.separator + imgName;}File file = new File(path);if (file.exists()) {file.delete();}File fileParent = file.getParentFile();if(!fileParent.exists()){fileParent.mkdirs();}file.createNewFile();String jsPath;// 区分服务器和本地环境if (OSUtil.isLinux()) {jsPath = "/usr/local/echarts/echarts-convert.js";} else {// resources下创建echarts文件夹jsPath = ResourceUtils.getURL("classpath:echarts").getPath() + File.separator + "echarts-convert.js";}log.info("start cmd exec generate png");cmd = "/usr/local/bin/phantomjs " + jsPath + " -options " + options + " -outfile " + path + " -width " + width + " -height " + height;log.info("cmd: {}", cmd);Process process = Runtime.getRuntime().exec(cmd);log.info("end cmd exec generate png");input = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = input.readLine()) != null) {log.info(line);}log.info("close");} catch (Exception e) {e.printStackTrace();log.error("echarts error: {}, cmd: {}, options: {}, imageName: {}", e.getMessage(), cmd, options, imgName, e);} finally {if (input != null) {try {input.close();} catch (IOException e) {e.printStackTrace();log.error("关闭流失败, {}, options: {}, imageName: {}", e.getMessage(), options, imgName, e);}}}return path;}/*** 折线图* @param types             y轴值* @param yColor            y轴颜色-多个请自行换类型* @param title             图表标题* @param titleAglin        标题对齐* @param rotate            横坐标旋转角度* @param interval          刻度间隔* @param xDataList         x轴值* @param yDataList         y轴值* @param axisName          横坐标名* @param isHorizontal      是否颠倒x与y轴* @return*/public String getLineEchartOption(String[] types, String yColor, String title, String titleAglin,Integer rotate, Integer interval, List<String> xDataList, List<String> yDataList, String axisName, boolean isHorizontal) {GsonOption option = new GsonOption();// 大标题、位置option.title().text(title).x(titleAglin);// 提示工具option.tooltip().show(true).trigger(Trigger.axis);// 工具栏option.toolbox().show(true).feature(Tool.mark, Tool.dataView, new MagicType(Magic.line, Magic.bar), Tool.restore, Tool.saveAsImage);// 图例for (String legend : types) {option.legend(legend);}// 循环给y轴赋值数据for (int i = 0; i < types.length; i++) {Line line = new Line();String type = types[i];line.name(type);for (String yy : yDataList) {line.data(yy);}option.series(line);}// 轴分类CategoryAxis x = new CategoryAxis();for (String cate : xDataList) {x.data(cate);}x.name(axisName);// 设置横坐标旋转角度AxisLabel xLabel = new AxisLabel();xLabel.setRotate(rotate);xLabel.setInterval(interval);x.setAxisLabel(xLabel);// 横轴为类别、纵轴为值if (isHorizontal) {// x轴option.xAxis(x);// y轴ValueAxis ecsY = new ValueAxis();ecsY.axisLine().lineStyle().color(yColor);option.yAxis(ecsY);} else {// 横轴为值、纵轴为类别// x轴option.xAxis(new ValueAxis());// y轴option.yAxis(x);}Grid grid = new Grid();// 控制x轴文字与左边的距离grid.setX(70);// 控制x2轴文字与右边的距离grid.setX2(100);// y2可以控制倾斜的文字与底部的距离grid.setY2(100);// y可以控制倾斜的文字与顶部的距离grid.setY(100);option.setGrid(grid);String optionStr = option.toString().replace(" ", "");log.info("line-options: {}", optionStr);return optionStr;}/*** 柱状图* @param types             y轴值* @param typeColors        y轴颜色* @param title             图表标题* @param titleAglin        标题对齐* @param rotate            横坐标旋转角度* @param interval          刻度间隔* @param xDataList         x轴值* @param yDataList         y轴值* @param axisName          横坐标名* @param isHorizontal      是否颠倒x与y轴* @return*/public String getBarEchartOption(String[] types, String[] typeColors, String title, String titleAglin,Integer rotate, Integer interval, String[] xDataList, Integer[] yDataList, String axisName, boolean isHorizontal) {GsonOption option = new GsonOption();// 大标题、位置option.title().text(title).x(titleAglin);//显示工具提示,设置提示格式option.tooltip().show(true).trigger(Trigger.axis);// 工具栏option.toolbox().show(true).feature(Tool.mark, Tool.dataView, new MagicType(Magic.line, Magic.bar), Tool.restore, Tool.saveAsImage);// 图例option.legend(types[0]);// 图类别(柱状图)Bar bar = new Bar(types[0]);int size = xDataList.length;if (size > 30) {bar.setBarWidth(5);} else {bar.setBarWidth(30);}// 循环数据for (int i = 0; i < size; i++) {String color = typeColors[i % typeColors.length];// 类目对应的柱状图/*** itemStyle: {* 				normal: {* 						label: {* 								show: true, //开启显示* 								position: 'top', //在上方显示* 								textStyle: { //数值样式* 								color: 'black',* 								fontSize: 16*                              }*                      }*              }* }*/Label label = new Label();label.show(true);label.position("top");TextStyle textStyle = new TextStyle();textStyle.color("black");textStyle.fontSize(16);label.textStyle(textStyle);ItemStyle itemStyle = new ItemStyle();Normal normal = new Normal();normal.color(color);normal.label(label);itemStyle.normal(normal);Map<String, Object> map = new HashMap<>(16);map.put("value", yDataList[i]);map.put("itemStyle", itemStyle);bar.data(map);}// 轴分类CategoryAxis x = new CategoryAxis();for (String cate : xDataList) {x.data(cate);}x.name(axisName);// 设置横坐标旋转角度AxisLabel xLabel = new AxisLabel();xLabel.setRotate(rotate);xLabel.setInterval(interval);x.setAxisLabel(xLabel);// 横轴为类别、纵轴为值if (isHorizontal) {// x轴option.xAxis(x);// y轴option.yAxis(new ValueAxis());} else {// 横轴为值、纵轴为类别// x轴option.xAxis(new ValueAxis());// y轴option.yAxis(x);}option.series(bar);Grid grid = new Grid();// 控制x轴文字与左边的距离grid.setX(70);// 控制x2轴文字与右边的距离grid.setX2(100);// y2可以控制倾斜的文字与底部的距离grid.setY2(100);// y可以控制倾斜的文字与顶部的距离grid.setY(100);option.setGrid(grid);String optionStr = option.toString().replace(" ", "");log.info("bar-options: {}", optionStr);return optionStr;}
}

这篇关于纯后台生成echarts图片-phantomjs-2.1.1的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/302641

相关文章

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

使用Python实现base64字符串与图片互转的详细步骤

《使用Python实现base64字符串与图片互转的详细步骤》要将一个Base64编码的字符串转换为图片文件并保存下来,可以使用Python的base64模块来实现,这一过程包括解码Base64字符串... 目录1. 图片编码为 Base64 字符串2. Base64 字符串解码为图片文件3. 示例使用注意

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

python如何生成指定文件大小

《python如何生成指定文件大小》:本文主要介绍python如何生成指定文件大小的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python生成指定文件大小方法一(速度最快)方法二(中等速度)方法三(生成可读文本文件–较慢)方法四(使用内存映射高效生成

c/c++的opencv实现图片膨胀

《c/c++的opencv实现图片膨胀》图像膨胀是形态学操作,通过结构元素扩张亮区填充孔洞、连接断开部分、加粗物体,OpenCV的cv::dilate函数实现该操作,本文就来介绍一下opencv图片... 目录什么是图像膨胀?结构元素 (KerChina编程nel)OpenCV 中的 cv::dilate() 函

Maven项目中集成数据库文档生成工具的操作步骤

《Maven项目中集成数据库文档生成工具的操作步骤》在Maven项目中,可以通过集成数据库文档生成工具来自动生成数据库文档,本文为大家整理了使用screw-maven-plugin(推荐)的完... 目录1. 添加插件配置到 pom.XML2. 配置数据库信息3. 执行生成命令4. 高级配置选项5. 注意事

MybatisX快速生成增删改查的方法示例

《MybatisX快速生成增删改查的方法示例》MybatisX是基于IDEA的MyBatis/MyBatis-Plus开发插件,本文主要介绍了MybatisX快速生成增删改查的方法示例,文中通过示例代... 目录1 安装2 基本功能2.1 XML跳转2.2 代码生成2.2.1 生成.xml中的sql语句头2

使用Python实现调用API获取图片存储到本地的方法

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接... 目录使用python实现调用API获取图片存储到本地1、项目概述2、核心功能3、环境准备4、代码实现