为了账号安全,请及时绑定邮箱和手机立即绑定

SpringBoot纯后台生成Echarts图片(二)

  https://img1.sycdn.imooc.com//5da6dbd10001602909000675.jpg

SpringBoot纯后台生成Echarts图片(一)

紧接 SpringBoot纯后台生成Echarts图片(一),在这篇的基础上,来生成折线图

一. 项目工程结构

https://img1.sycdn.imooc.com//5da6d0ff0001855d04210683.jpg

二.项目依赖说明

项目的pom.xml配置,属性配置 见第一篇

三.项目代码说明

(1)echarts-pojo模块(数据模型)LinesData.java  

package com.lhf.springboot.echarts.pojo;

/**
 * @ClassName: LineData
 * @Author: liuhefei
 * @Description: TODD
 * @Date: 2019/8/15 19:11
 */
public class LinesData {

      private String title;

    private LineParam lineParam;

    private boolean isHorizontal = true;

    //省略get/set方法
}


(2)echarts-pojo模块(数据模型)LineParam.java

package com.lhf.springboot.echarts.pojo;

import java.util.List;

/**
 * @ClassName: LineParam
 * @Author: liuhefei
 * @Description: TODD
 * @Date: 2019/8/15 19:35
 */
public class LineParam {

      private String legendName;

    private String[] ydatas;

    private List<Object[]> xdatas;

    //省略get/set方法
}

(3)echarts-option模块(组装图表option)-EchartLine.java(组装折线图option)(核心)

package com.lhf.springboot.echarts.option;


import com.github.abel533.echarts.Legend;
import com.github.abel533.echarts.axis.AxisLabel;
import com.github.abel533.echarts.axis.AxisLine;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Position;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.style.LineStyle;
import com.github.abel533.echarts.style.TextStyle;
import com.github.abel533.echarts.style.itemstyle.Normal;
import com.lhf.springboot.echarts.EnhancedOption;
import com.lhf.springboot.echarts.pojo.LinesData;

import java.util.List;

/**
 * @ClassName: EchartLine
 * @Author: liuhefei
 * @Description: TODD
 * @Date: 2019/8/15 19:10
 */
public class EchartLine {

    public static GsonOption createLine(LinesData linesData){

        //String[] types = { "邮件营销", "联盟广告", "视频广告" };
        //int[][] datas = { { 120, 132, 101, 134, 90, 230, 210 }, { 220, 182, 191, 234, 290, 330, 310 }, { 150, 232, 201, 154, 190, 330, 410 } };
        //String title = "广告数据";

        String title = linesData.getTitle();
        String legendName = linesData.getLineParam().getLegendName();
        String[] ydatas = linesData.getLineParam().getYdatas();
        boolean isHorizontal = linesData.isHorizontal();

        //String[] types = legendName;
        String[] types = {title};
        //int[][] xdatas = { { 120, 132, 101, 134, 90, 230, 210 }, { 220, 182, 191, 234, 290, 330, 310 }, { 150, 232, 201, 154, 190, 330, 410 } };
        List<Object[]> xdatas = linesData.getLineParam().getXdatas();


        Line line = new Line();  //三条线三个对象
        EnhancedOption option = new EnhancedOption();

        //文本样式
        TextStyle textStyle = new TextStyle();
        textStyle.color("red");
        textStyle.fontSize(15);
        textStyle.fontWeight("bolder");

        //title
        option.title().text(title).subtext("").x("left");  //大标题,小标题,位置
        //文本样式
        option.title().textStyle(textStyle);  //标题文本样式


        //提示工具 tooltip
        option.tooltip().trigger(Trigger.axis);// 在轴上触发提示数据
        //工具栏 toolbox
        //option.toolbox().show(true).feature(Tool.saveAsImage); //显示保存为图片

        //图例 legend
        Legend legend = new Legend();
        option.legend(legendName);  //图例
        option.legend().textStyle(textStyle); //图例文本样式

        //axisLabel
        AxisLabel axisLabel = new AxisLabel();
        TextStyle textStyle1 = new TextStyle();
        textStyle1.fontSize(15);
        textStyle1.fontWeight("bolder");
        axisLabel.show(true);
        axisLabel.textStyle(textStyle1);

        //axisLine
        AxisLine axisLine = new AxisLine();
        LineStyle lineStyle = new LineStyle();  //坐标轴样式
        lineStyle.color("#315070");
        lineStyle.width(4);
        axisLine.lineStyle(lineStyle);

        //xAxis
        CategoryAxis category = new CategoryAxis();  //轴分类
        category.data(ydatas);
        category.boundaryGap(false);// 起始和结束两端空白策略
        category.axisLabel(axisLabel);  //x轴文字样式
        category.axisLine(axisLine);  //x轴样式

        //yAxis
        ValueAxis valueAxis = new ValueAxis();
        valueAxis.axisLabel().show(true).textStyle().fontSize(15).fontWeight("bolder");  //y轴文字样式
        valueAxis.axisLine().lineStyle().color("#315070").width(4);  //y轴样式


        line.setSmooth(true);   //平滑曲线
        line.setShowAllSymbol(true); //标志图形默认只有主轴显示(随主轴标签间隔隐藏策略),如需全部显示可把showAllSymbol设为true
        line.setSymbolSize("15");  //点大小
        line.setDataFilter("nearest"); //在折线图的数据数量大于实际显示的像素宽度(高度)的时候会启用优化
        line.setLegendHoverLink(true); //是否启用图例(legend)hover时的联动响应(高亮显示)

        Normal normal = new Normal();
        normal.setShow(true);  //是否显示数据
        normal.color("green");  //数据颜色
        normal.position(Position.right); //数据显示位置
        line.label().normal(normal);

        LineStyle lineStyle1 = new LineStyle();   //折线样式
        lineStyle1.color("green");  //线颜色
        lineStyle1.width(4);  //线宽
        line.lineStyle(lineStyle1);

        //循环数据
        for(int i=0;i<types.length;i++){
            String type = types[i];
            line.name(legendName.toString()).stack("总量");
            for(int j = 0; j< xdatas.get(i).length; j++){
                line.data(xdatas.get(i)[j]);
            }
            option.series(line);
        }

        if(isHorizontal){  //横轴为类别,纵轴为值
            option.xAxis(category);  //x轴
            option.yAxis(valueAxis);  //y轴
        }else {  //横轴为值,纵轴为类别
            option.xAxis(valueAxis);  //x轴
            option.yAxis(category);  //y轴
        }

        //System.out.println("option=" + option);

        return option;

    }
}

(4)controller模块(API接口)- EchartsController.java

package com.lhf.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.abel533.echarts.json.GsonOption;
import com.lhf.springboot.common.JsonResult;
import com.lhf.springboot.echarts.option.EchartBar;
import com.lhf.springboot.echarts.option.EchartLine;
import com.lhf.springboot.echarts.option.EchartPie;
import com.lhf.springboot.echarts.pojo.BarData;
import com.lhf.springboot.echarts.pojo.LinesData;
import com.lhf.springboot.echarts.pojo.PieData;
import com.lhf.springboot.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: EchartsController
 * @Author: liuhefei
 * @Description: 利用Java代码生成柱状图和折线图
 * @Date: 2019/9/26 10:37
 */
@Api(value = "生成Echarts图表API接口", tags = "Echarts图表")
@RequestMapping("/echarts")
@RestController
public class EchartsController {

    private final static Logger logger = Logger.getLogger(EchartsController.class);

   @Value("${img-url}")
    private String imgUrl;

   @Value("${img-url-path}")
    private String imgUrlPath;

   @Value("${request-url}")
    private String requestUrl;

    @ApiOperation(value = "生成折线图")
    @RequestMapping(value = "/line", method = RequestMethod.POST)
    public JsonResult createLine(@RequestBody LinesData linesData){

        GsonOption option = (GsonOption) EchartLine.createLine(linesData);

        String optionStr = JSONObject.toJSONString(option);

        if(optionStr == null || "".equals(optionStr)){
            return new JsonResult(-1, "Fail");
        }

        logger.info("line-optionStr = " + optionStr);

        File oldfile = null;
        File newfile = null;
        String oldFilePath = null;
        String newFilePath = null;

        try{
            // 根据option参数发起请求,转换为base64
            String base64Code =  EchartsUtil.generateEchartsBase64(optionStr, requestUrl);


            /*时间格式化*/
            //String nowStr = FastDateFormat.getInstance("yyyyMMddHHmmss").format(new Date());
            long nowStr = Calendar.getInstance().getTimeInMillis();
            String imageName = "line"+nowStr+ RandomUtils.getRandomString(4)+".png";
            logger.info("line图片:" + imageName);

            oldfile = FileUtil.generateImage(base64Code, imgUrl+imageName);
            newfile = new File(imgUrl+"new"+imageName);
            logger.info("file = " + oldfile);

            oldFilePath = imgUrl+imageName;
            newFilePath = imgUrl+"new"+imageName;
            logger.info("file = " + oldfile);

            logger.info("oldFilePath = " + oldFilePath);
            logger.info("newFilePath = " + newFilePath);

            String logoText = "霜花似雪";

            //添加水印
            ImageUtil.markImageByText(logoText, oldFilePath, newFilePath, -15, new Color(190,190,190), "png");


        }catch (Exception e){
            logger.error("发生了异常," + e.getMessage());
            return new JsonResult(-1, "Fail");
        }
        return new JsonResult(1,  newFilePath, "SUCCESS");
    }

    
}

(5)其他模块的相关代码见第一篇

四.插件环境配置

插件环境配置见第一篇说明

五.结合swagger文档测试

启动服务,访问swagger文档地址:http://localhost:8095/swagger-ui.html

测试数据:

{
  "horizontal": true,
  "lineParam": {
    "legendName": "胸罩图例",
    "xdatas": [
      [
       43364, 13899, 12000, 2181, 21798, 1796, 1300
      ]
    ],
    "ydatas": [
        "A罩杯", "B罩杯", "C罩杯", "D罩杯", "E罩杯", "F罩杯","G罩杯"
    ]
  },
  "title": "胸罩使用人数"
}

效果展示:

https://img1.sycdn.imooc.com//5da6d7f20001e75b08000400.jpg

https://img1.sycdn.imooc.com//5da6d8040001032f08000400.jpg

今天的分享就到这里,未完待续!

为大家推荐几门实战课程,来提升一下自己:

(1)Spring Boot打造企业级微信点餐系统

(2)Java秒杀系统高并发实战

(3)Java大数据实战 Storm构建实时流处理

(4)Java从单体到微服务打造房产销售平台


点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
1.5万
获赞与收藏
8507

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消