适用场景:前台展示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生成的图片文件路径,然后就跟正常使用图片一样啦。