纯后台生成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实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Java利用docx4j+Freemarker生成word文档

《Java利用docx4j+Freemarker生成word文档》这篇文章主要为大家详细介绍了Java如何利用docx4j+Freemarker生成word文档,文中的示例代码讲解详细,感兴趣的小伙伴... 目录技术方案maven依赖创建模板文件实现代码技术方案Java 1.8 + docx4j + Fr

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

详解C#如何提取PDF文档中的图片

《详解C#如何提取PDF文档中的图片》提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使用,下面我们就来看看如何使用C#通过代码从PDF文档中提取图片吧... 当 PDF 文件中包含有价值的图片,如艺术画作、设计素材、报告图表等,提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使