纯后台生成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

相关文章

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

关于MongoDB图片URL存储异常问题以及解决

《关于MongoDB图片URL存储异常问题以及解决》:本文主要介绍关于MongoDB图片URL存储异常问题以及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录MongoDB图片URL存储异常问题项目场景问题描述原因分析解决方案预防措施js总结MongoDB图

python实现svg图片转换为png和gif

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录python实现svg图片转换为png和gifpython实现图片格式之间的相互转换延展:基于Py

使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)

《使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)》PPT是一种高效的信息展示工具,广泛应用于教育、商务和设计等多个领域,PPT文档中常常包含丰富的图片内容,这些图片不仅提升了... 目录一、引言二、环境与工具三、python 提取PPT背景图片3.1 提取幻灯片背景图片3.2 提取

Python实现图片分割的多种方法总结

《Python实现图片分割的多种方法总结》图片分割是图像处理中的一个重要任务,它的目标是将图像划分为多个区域或者对象,本文为大家整理了一些常用的分割方法,大家可以根据需求自行选择... 目录1. 基于传统图像处理的分割方法(1) 使用固定阈值分割图片(2) 自适应阈值分割(3) 使用图像边缘检测分割(4)

C#实现将Excel表格转换为图片(JPG/ PNG)

《C#实现将Excel表格转换为图片(JPG/PNG)》Excel表格可能会因为不同设备或字体缺失等问题,导致格式错乱或数据显示异常,转换为图片后,能确保数据的排版等保持一致,下面我们看看如何使用C... 目录通过C# 转换Excel工作表到图片通过C# 转换指定单元格区域到图片知识扩展C# 将 Excel

IDEA自动生成注释模板的配置教程

《IDEA自动生成注释模板的配置教程》本文介绍了如何在IntelliJIDEA中配置类和方法的注释模板,包括自动生成项目名称、包名、日期和时间等内容,以及如何定制参数和返回值的注释格式,需要的朋友可以... 目录项目场景配置方法类注释模板定义类开头的注释步骤类注释效果方法注释模板定义方法开头的注释步骤方法注

JS+HTML实现在线图片水印添加工具

《JS+HTML实现在线图片水印添加工具》在社交媒体和内容创作日益频繁的今天,如何保护原创内容、展示品牌身份成了一个不得不面对的问题,本文将实现一个完全基于HTML+CSS构建的现代化图片水印在线工具... 目录概述功能亮点使用方法技术解析延伸思考运行效果项目源码下载总结概述在社交媒体和内容创作日益频繁的

Python如何自动生成环境依赖包requirements

《Python如何自动生成环境依赖包requirements》:本文主要介绍Python如何自动生成环境依赖包requirements问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录生成当前 python 环境 安装的所有依赖包1、命令2、常见问题只生成当前 项目 的所有依赖包1、

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例