java获取echarts图表(饼图,柱状图,折线图等等)

本文介绍如何在前端使用ECharts生成饼图、柱状图等,并将其转换为图片保存到本地。通过获取echarts图的DataURL,使用AJAX向后台发送请求,后台通过Base64解码将图片数据保存,最终返回图片文件路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

适用场景:前台展示echarts饼图,柱状图,折线图等等,后台生成文档或者其他需要把图片获取到

1.前台echarts图搭建

<!-- 引入 ECharts 文件 -->
    <script src="echarts.min.js"></script>
<body>
    <!-- 为 ECharts 准备一个具备大小(宽高)的 DOM -->
    <div id="main" style="width: 600px;height:400px;"></div>
</body>
<script type="text/javascript">
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('main'));

        // 指定图表的配置项和数据
        var option = {
            title: {
                text: 'ECharts 入门示例'
            },
            tooltip: {},
            legend: {
                data:['销量']
            },
            xAxis: {
                data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
            },
            yAxis: {},
            series: [{
                name: '销量',
                type: 'bar',
                data: [5, 20, 36, 10, 10, 20]
            }]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    </script>

 

上面是一个官方例子,怎么获取这个图呢?使用  var barImg = myChart.getDataURL();

获取到这个图的url,然后向后台发起请求,转化为图片保存到本地,方便后面使用

$.ajax({
                type: "post",
                data: {
                    imageFile: barImg
                },
                url: 'Controller.do?getChartImage',
                async: false,
                success: function(data) {
                   //返回文件名

                    var imgInfo=data;
                },
                error: function(err){
                    console.log('图片保存失败');
                }
            });

2.后台:

/**
     * 接收前端传过来的base64图片
     * @return
     */
    @RequestMapping(params ="getChartImage")
    @ResponseBody
    public String getChartImage(String imageFile){
         // 通过base64来转化图片
        imageFile = imageFile.replaceAll("data:image/png;base64,", "");      
        Base64Encoder decoder = new Base64Encoder();
        // Base64解码      
        byte[] imageByte = null;
        String chartImage = null ;
        try {
            imageByte = decoder.decode(imageFile);      
            for (int i = 0; i < imageByte.length; ++i) {      
                if (imageByte[i] < 0) {// 调整异常数据      
                    imageByte[i] += 256;      
                }      
            }     
            // 将二进制转换成图片
            chartImage = getChartImageByBate(imageByte);
        } catch (Exception e) {
             e.printStackTrace(); 
        }
        return chartImage;
    }
    public String getChartImageByBate(byte[]  imageFile){
         // 生成文件名
        String files = new SimpleDateFormat("yyyyMMddHHmmssSSS")
                .format(new Date())
                + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000)
                + ".png";
        // 生成文件路径
        String filename = "d://" + files;;     
        try {
            File filePack =new File("d://") ;
            if(!filePack.exists() && !filePack.isDirectory()){
                filePack.mkdir();
            }
                // 生成文件         
                File imageFiles = new File(filename);
                imageFiles.createNewFile();
                if(!imageFiles.exists()){
                    imageFiles.createNewFile();
                }
                OutputStream imageStream = new FileOutputStream(imageFiles);
                imageStream.write(imageFile);
                imageStream.flush();
                imageStream.close();                
        } catch (Exception e) {         
            e.printStackTrace();
        }
        return files;
    }

到这里,前台就获取到了echarts生成的图片文件路径,然后就跟正常使用图片一样啦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值