Springboot Echarts生成图片保存到本地

package com.xcx.spots.entity;

import java.awt.;
import java.io.File;
import java.util.
;

import javax.imageio.ImageIO;

import com.xcx.spots.controller.api.JiffCDemo;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import java.util.List;
import java.util.Map.Entry;

public class BingUtils {

public static String  createPort(String title, Map<String, Double> datas, Font font){
    try {
        //如果不使用Font,中文将显示不出来

        DefaultPieDataset pds = new DefaultPieDataset();

        //获取迭代器:
        Set<Entry<String, Double>> set =  datas.entrySet();
        Iterator iterator=(Iterator) set.iterator();
        Entry entry=null;
        while(iterator.hasNext()){
            entry=(Entry) iterator.next();
            pds.setValue(entry.getKey().toString(),Double.parseDouble(entry.getValue().toString()));
        }
        /**
         45                  * 生成一个饼图的图表
         46                  *
         47                  * 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接
         48                  */
        JFreeChart chart = ChartFactory.createPieChart(title, pds, true, false, true);
        //设置图片标题的字体
        chart.getTitle().setFont(font);

        //得到图块,准备设置标签的字体
        PiePlot plot = (PiePlot) chart.getPlot();

        //设置分裂效果,需要指定分裂出去的key
        plot.setExplodePercent("天使-彦", 0.1);

        //设置标签字体
        plot.setLabelFont(font);

        //设置图例项目字体
        chart.getLegend().setItemFont(font);

        /**
         66                  * 设置开始角度(弧度计算)
         67                  *
         68                  * 度    0°    30°        45°        60°        90°        120°    135°    150°    180°    270°    360°
         69                  * 弧度    0    π/6        π/4        π/3        π/2        2π/3    3π/4    5π/6    π        3π/2    2π
         70                  */
        plot.setStartAngle(new Float(3.14f / 2f));

        //设置背景图片,设置最大的背景
        Image img = ImageIO.read(new File("f:/test/1.jpg"));
        chart.setBackgroundImage(img);

        //设置plot的背景图片
        img = ImageIO.read(new File("f:/test/2.jpg"));
        plot.setBackgroundImage(img);

        //设置plot的前景色透明度
        plot.setForegroundAlpha(0.7f);

        //设置plot的背景色透明度
        plot.setBackgroundAlpha(0.0f);

        //设置标签生成器(默认{0})
        //{0}:key {1}:value {2}:百分比 {3}:sum
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1}道题)/{2}"));

        //将内存中的图片写到本地硬盘
        UUID uuid = UUID.randomUUID();
        ChartUtilities.saveChartAsJPEG(new File("C:/Users/nh/Documents/a/spots/src/main/resources/static/images/"+uuid+".png"), chart, 600, 300);
        String s="C:/Users/nh/Documents/a/spots/src/main/resources/static/images/"+uuid+".png";
        return s;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
public static void main(String[] args) {
    Font font = new Font("新宋体", Font.BOLD, 15);
    Map<String, Double> map=new HashMap<String, Double>();
    map.put("A(优秀)", (double) 1000);
    map.put("B(良好)", (double) 700);
    map.put("C(及格)", (double) 600);
    map.put("D(不及格)", (double) 400);
  String s=  BingUtils.createPort("超神学院女神投票结果", map, font);
    System.out.println(s);
}

}
package com.xcx.spots.entity;

import org.apache.commons.lang.StringUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import java.awt.
;
import java.io.File;
import java.io.FileOutputStream;

/**

  • @ProjectName: spots
  • @Package: com.xcx.spots.entity
  • @ClassName: ZheUtils
  • @Author: nh
  • @Description:
  • @Date: 2020/6/22 16:41
  • @Version: 1.0
    */

public class ZheUtils {
private String imgpath;

public String getImgpath() {
    if(StringUtils.isEmpty(imgpath)){
        return "C:\\Users\\nh\\Documents\\a\\spots\\src\\main\\resources\\static\\images\\";
    }
    return imgpath;
}

public void setImgpath(String imgpath) {
    this.imgpath = imgpath;
}

/**
 * 创建简单折线图
 * @param rowKeys
 * @param colKeys
 * @param data
 * @param charName
 * @return
 */
public String createTimeXYCharSimple(String[] rowKeys, String[] colKeys, double[][] data, String charName){
    CategoryDataset xyDataset = DatasetUtilities.createCategoryDataset(rowKeys, colKeys, data);
    return createTimeXYChar("", "", "", xyDataset, charName, false, 0, 0, 1);
}

/**
 * 创建简单折线图(设置刻度)
 * @param rowKeys
 * @param colKeys
 * @param data
 * @param charName
 * @param min	刻度最小值
 * @param max	刻度最大值
 * @param size	刻度间隔
 * @return
 */
public String createTimeXYCharSimpleSetBoundAndTick(String[] rowKeys, String[] colKeys, double[][] data, String charName, double min, double max, double size){
    CategoryDataset xyDataset = DatasetUtilities.createCategoryDataset(rowKeys, colKeys, data);
    return createTimeXYChar("", "", "", xyDataset, charName, true, min, max, size);
}

/**
 * 折线图
 *
 * @param chartTitle
 * @param x
 * @param y
 * @param xyDataset
 * @param charName
 * @param min	刻度最小值
 * @param max	刻度最大值
 * @param size	刻度间隔
 * @return
 */
public String createTimeXYChar(String chartTitle, String x, String y, CategoryDataset xyDataset, String charName, boolean flag, double min, double max, double size) {

    //ChartFactory.createLineChart3D创建3D折线图
    JFreeChart chart = ChartFactory.createLineChart(chartTitle, //标题
            x, //x轴标签
            y, //y轴标签
            xyDataset, //数据源
            PlotOrientation.VERTICAL, //图表方向:水平、垂直
            true, //是否显示图例(对于简单的柱状图必须是false)
            true, //是否生成工具
            false); //是否生成URL链接

    //字体
    Font titlefont = new Font("宋体", Font.BOLD, 25);
    Font labelFont = new Font("宋体", Font.CENTER_BASELINE, 12);

    chart.setTextAntiAlias(false);
    // 设置背景色
    chart.setBackgroundPaint(Color.WHITE);
    // 重设标题
    TextTitle title = new TextTitle(chartTitle);
    title.setFont(titlefont);
    chart.setTitle(title);
    // 设置选项字体
    chart.getLegend().setItemFont(labelFont);

    //获取图表主体
    CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();

    // x轴
    categoryplot.setDomainGridlinesVisible(true);//设置网格是否可见
    categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩
    // y轴
    categoryplot.setRangeGridlinesVisible(true);//设置网格是否可见
    categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩

    categoryplot.setBackgroundPaint(Color.lightGray);//图表背景色

    // 设置轴和面板之间的距离
    // categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));

    // x轴
    CategoryAxis domainAxis = categoryplot.getDomainAxis();
    domainAxis.setLabelFont(labelFont);// 轴标题字体
    domainAxis.setTickLabelFont(labelFont);// 轴数值字体
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 轴标题45度倾斜
    // y轴
    ValueAxis valueAxis = categoryplot.getRangeAxis();
    valueAxis.setLabelFont(labelFont);// 轴标题字体
    if(flag){
        valueAxis.setLowerBound(min);
        valueAxis.setUpperBound(max);
    }
    NumberAxis numAxis = (NumberAxis) categoryplot.getRangeAxis();
    numAxis.setTickUnit(new NumberTickUnit(size));//设置Y轴间隔


    // 设置距离图片左端距离
    domainAxis.setLowerMargin(0.0);
    // 设置距离图片右端距离
    domainAxis.setUpperMargin(0.0);

    NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
    numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    numberaxis.setAutoRangeIncludesZero(true);

    LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();
    lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见
    lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见

    // 显示折点数据
    lineandshaperenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    lineandshaperenderer.setBaseItemLabelsVisible(false);

    FileOutputStream fos_jpg = null;
    try {
        isChartPathExist(getImgpath());
        String chartName = getImgpath() + charName;
        fos_jpg = new FileOutputStream(chartName);

        // 将报表保存为jpeg文件
        ChartUtilities.writeChartAsJPEG(fos_jpg, chart, 600, 400);

        return chartName;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            fos_jpg.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * 判断文件夹是否存在,如果不存在则新建
 * @param chartPath
 */
public void isChartPathExist(String chartPath) {
    File file = new File(chartPath);
    if (!file.exists()) {
        file.mkdirs();
    }
}

public static void main(String[] args){

    //可以设置y轴的刻度
    ZheUtils chartUtil1 = new ZheUtils();
    double[][] data1 = new double[][] {{ 0, 0, 0, 0},{ 20, 30, 70, 80} };
    String[] rowKeys1 = {"A","B" };
    String[] colKeys1 = { "周测一", "周测二", "周测三", "周测四" };
   String name= chartUtil1.createTimeXYCharSimpleSetBoundAndTick(rowKeys1, colKeys1, data1, "aa1.jpg", 0, 100, 5);
    System.out.println(name);
}

}
]package com.xcx.spots.entity;

import java.awt.;
import java.io.File;
import java.util.
;

import javax.imageio.ImageIO;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import sun.plugin.util.UIUtil;

import java.util.List;
import java.util.Map.Entry;

/**

  • @ProjectName: spots
  • @Package: com.xcx.spots.entity
  • @ClassName: ZhuUtils
  • @Author: nh
  • @Description:
  • @Date: 2020/6/22 16:42
  • @Version: 1.0
    */

public class ZhuUtils {

/**
 * 提供静态方法:获取报表图形2:柱状图
 * @param title        标题
 * @param datas        数据
 * @param type        分类(第一季,第二季.....)
 * @param danwei    柱状图的数量单位
 * @param font        字体
 */
    public static String createPort(String title, Map<String, Map<String,Double>> datas, String type, String danwei, Font font){
        try {
            //种类数据集
            DefaultCategoryDataset ds = new DefaultCategoryDataset();


            //获取迭代器:
            Set<Map.Entry<String, Map<String, Double>>> set1 =  datas.entrySet();    //总数据
            Iterator iterator1=(Iterator) set1.iterator();                        //第一次迭代
            Iterator iterator2=null;
            HashMap<String, Double> map =  null;
            Set<Map.Entry<String,Double>> set2=null;
            Map.Entry entry1=null;
            Map.Entry entry2=null;

            while(iterator1.hasNext()){
                entry1=(Map.Entry) iterator1.next();                    //遍历分类

                map=(HashMap<String, Double>) entry1.getValue();//得到每次分类的详细信息
                set2=map.entrySet();                               //获取键值对集合
                iterator2=set2.iterator();                        //再次迭代遍历
                while (iterator2.hasNext()) {
                    entry2= (Map.Entry) iterator2.next();
                    ds.setValue(Double.parseDouble(entry2.getValue().toString()),//每次统计数量
                            entry2.getKey().toString(),                         //名称
                            entry1.getKey().toString());                        //分类
                    System.out.println("当前:--- "+entry2.getKey().toString()+"--"
                            +entry2.getValue().toString()+"--"
                            +entry1.getKey().toString());
                }
                System.out.println("-------------------------------------");
            }

            //创建柱状图,柱状图分水平显示和垂直显示两种//
            JFreeChart chart = ChartFactory.createBarChart(title, type, danwei, ds, PlotOrientation.VERTICAL, true, true, true);
            //设置整个图片的标题字体
            chart.getTitle().setFont(font);
            //设置提示条字体
            font = new Font("宋体", Font.BOLD, 15);
            chart.getLegend().setItemFont(font);

            //得到绘图区
            CategoryPlot plot = chart.getCategoryPlot();//
            //得到绘图区的域轴(横轴),设置标签的字体
            plot.getDomainAxis().setLabelFont(font);
            Color c = new Color(36,63,110);
            plot.getRenderer().setSeriesPaint(0,c) ;//设置第一个柱子的颜色
            plot.getRenderer().setSeriesPaint(1,new Color(0,128,11)) ;

            //设置横轴标签项字体
            plot.getDomainAxis().setTickLabelFont(font);

            //设置范围轴(纵轴)字体
            plot.getRangeAxis().setLabelFont(font);
            //存储成图片

            //设置chart的背景图片
            chart.setBackgroundImage(ImageIO.read(new File("f:/test/1.jpg")));

            plot.setBackgroundImage(ImageIO.read(new File("f:/test/2.jpg")));

            plot.setForegroundAlpha(1.0f);
            UUID uuid = UUID.randomUUID();
            ChartUtilities.saveChartAsJPEG(new File("C:/Users/nh/Documents/a/spots/src/main/resources/static/images/"+uuid+".png"), chart, 600, 400);
            String s ="C:/Users/nh/Documents/a/spots/src/main/resources/static/images/"+uuid+".png";
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        Map<String, Map<String, Double>> datas =new HashMap<String, Map<String,Double>>();
        Map<String, Double> map1=new HashMap<String, Double>();
        Map<String, Double> map2=new HashMap<String, Double>();
        Map<String, Double> map3=new HashMap<String, Double>();
        Map<String, Double> map4=new HashMap<String, Double>();
        //设置第一期的投票信息
        map1.put("天使-彦", (double) 600);
        map1.put("雄兵连-蔷薇", (double) 700);


        //设置第二期的投票信息
        map2.put("天使-彦", (double) 1300);
        map2.put("雄兵连-蔷薇", (double) 900);


        //设置第三期的投票信息
        map3.put("天使-彦", (double) 2000);
        map3.put("雄兵连-蔷薇", (double) 1700);


        //设置第四期的投票信息
        map4.put("天使-彦", (double) 3000);
        map4.put("雄兵连-蔷薇", (double) 2500);


        //压入数据
        datas.put("第一季", map1);
        datas.put("第二季", map2);
        datas.put("第三季-神与神", map3);
        // datas.put("第四季-黑甲", map4);

        Font font = new Font("宋体", Font.BOLD, 20);
        ZhuUtils.createPort("均分差",datas,"学生","单位(分)",font);
    }

}
package com.xcx.spots.entity;

import java.awt.;
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.
;

import javax.imageio.ImageIO;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import sun.plugin.util.UIUtil;

import java.util.List;
import java.util.Map.Entry;

public class SZUtils {

/**
 * 提供静态方法:获取报表图形2:柱状图
 * @param title        标题
 * @param datas        数据
 * @param type        分类(第一季,第二季.....)
 * @param danwei    柱状图的数量单位
 * @param font        字体
 */
    public static String createPort(String title,Map<String,Map<String,Double>> datas,String type,String danwei,Font font){
        try {
            //种类数据集
            DefaultCategoryDataset ds = new DefaultCategoryDataset();


            //获取迭代器:
            Set<Entry<String, Map<String, Double>>> set1 =  datas.entrySet();    //总数据
            Iterator iterator1=(Iterator) set1.iterator();                        //第一次迭代
            Iterator iterator2=null;
            HashMap<String, Double> map =  null;
            Set<Entry<String,Double>> set2=null;
            Entry entry1=null;
            Entry entry2=null;

            while(iterator1.hasNext()){
                entry1=(Entry) iterator1.next();                    //遍历分类

                map=(HashMap<String, Double>) entry1.getValue();//得到每次分类的详细信息
                set2=map.entrySet();                               //获取键值对集合
                iterator2=set2.iterator();                        //再次迭代遍历
                while (iterator2.hasNext()) {
                    entry2= (Entry) iterator2.next();
                    ds.setValue(Double.parseDouble(entry2.getValue().toString()),//每次统计数量
                            entry2.getKey().toString(),                         //名称
                            entry1.getKey().toString());                        //分类
                    System.out.println("当前:--- "+entry2.getKey().toString()+"--"
                            +entry2.getValue().toString()+"--"
                            +entry1.getKey().toString());
                }
                System.out.println("-------------------------------------");
            }

            //创建柱状图,柱状图分水平显示和垂直显示两种
            JFreeChart chart = ChartFactory.createBarChart(title, type, danwei, ds, PlotOrientation.VERTICAL, true, true, true);

            //设置整个图片的标题字体
            chart.getTitle().setFont(font);

            //设置提示条字体
            font = new Font("宋体", Font.BOLD, 15);
            chart.getLegend().setItemFont(font);

            //得到绘图区
            CategoryPlot plot = (CategoryPlot) chart.getPlot();
            //得到绘图区的域轴(横轴),设置标签的字体
            plot.getDomainAxis().setLabelFont(font);
            Color c = new Color(36,63,110);
            plot.getRenderer().setSeriesPaint(0,c) ;//设置第一个柱子的颜色
            plot.getRenderer().setSeriesPaint(1,new Color(0,128,11)) ;//第二个柱子颜色
            //Y轴刻度为整数从0开始
            NumberAxis localNumberAxis = (NumberAxis)plot.getRangeAxis();
            localNumberAxis.setNumberFormatOverride(NumberFormat.getNumberInstance());
            localNumberAxis.setUpperMargin(1);

              //设置横轴标签项字体
            plot.getDomainAxis().setTickLabelFont(font);
            CategoryPlot plotBar =  chart.getCategoryPlot();
            NumberAxis na= (NumberAxis)plotBar.getRangeAxis();
            na.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
            //设置范围轴(纵轴)字体
            plot.getRangeAxis().setLabelFont(font);
            //存储成图片

            //设置chart的背景图片
            chart.setBackgroundImage(ImageIO.read(new File("f:/test/1.jpg")));

            plot.setBackgroundImage(ImageIO.read(new File("f:/test/2.jpg")));

            plot.setForegroundAlpha(1.0f);

            UUID uuid = UUID.randomUUID();
            ChartUtilities.saveChartAsJPEG(new File("C:/Users/nh/Documents/a/spots/src/main/resources/static/images/"+uuid+".png"), chart, 600, 400);
            String s ="C:/Users/nh/Documents/a/spots/src/main/resources/static/images/"+uuid+".png";
            return s;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {


        Map<String, Map<String, Double>> datas =new HashMap<String, Map<String,Double>>();
        Map<String, Double> map1=new HashMap<String, Double>();
        Map<String, Double> map2=new HashMap<String, Double>();
        Map<String, Double> map3=new HashMap<String, Double>();
        Map<String, Double> map4=new HashMap<String, Double>();

        //设置第一期的投票信息
        map1.put("天使-彦", (double) 40);
        map1.put("雄兵连-蔷薇", (double) 12);
        //设置第二期的投票信息
        map2.put("天使-彦", (double) 70);
        map2.put("雄兵连-蔷薇", (double) 50);

        //设置第三期的投票信息
        map3.put("天使-彦", (double) 20);
        map3.put("雄兵连-蔷薇", (double) 10);
        //设置第四期的投票信息
        map4.put("天使-彦", (double) 30);
        map4.put("雄兵连-蔷薇", (double) 20);

        //压入数据
        datas.put("第一季", map1);
        datas.put("第二季", map2);
        datas.put("第三季", map3);
        datas.put("第四季", map4);

        Font font = new Font("宋体", Font.BOLD, 20);
        SZUtils.createPort("超神学院前四季最受欢迎的女性角色投票结果",datas,"超神纪元","百分比(%)",font);
    }

}

©️2020 CSDN 皮肤主题: 游动-白 设计师: 上身试试 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值