java后端生成echarts圖片

一、所需工具

1、phantomjs

官網(wǎng)下載http://phantomjs.org/download.html 國(guó)內(nèi)鏡像http://npm.taobao.org/dist/phantomjs/

2、EChartsConvert

https://gitee.com/saintlee/echartsconvert

二、Maven依賴

<dependency>

  <groupId>org.freemarker</groupId>

  <artifactId>freemarker</artifactId>

  <version>2.3.28</version>

</dependency>

<dependency>

  <groupId>org.apache.httpcomponents</groupId>

  <artifactId>httpclient</artifactId>

  <version>4.5.7</version>

</dependency>

<dependency>

  <groupId>com.alibaba</groupId>

  <artifactId>fastjson</artifactId>

  <version>1.2.56</version>

</dependency>

三、運(yùn)行EchartsConvert

1、安裝phantomjs、EchartsConvert

解壓 phantomjs-2.1.1-windows.zipsaintlee-echartsconvert-master.zip

2、命令行輸入指令

命令行輸入<phantomjs路徑> <EChartsConvert路徑> -s -p <服務(wù)端口號(hào)>
筆者沒(méi)有配置環(huán)境變量,完整輸入為

C:\Users\Administrator\Desktop\phantomjs-2.1.1-windows\bin>phantomjs C:\Users\Administrator\Desktop\echartsconvert\echarts-convert.js -s -p 6666

顯示echarts-convert server start success. [pid]=10364表明啟動(dòng)成功

四、java代碼

1、結(jié)構(gòu)

image.png

2、工具類

Http工具類

package com.mosband.genecharts.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

    public static String post(String url, Map<String, String> params, String charset)
            throws ClientProtocolException, IOException {
        String responseEntity = "";

        // 創(chuàng)建CloseableHttpClient對(duì)象
        CloseableHttpClient client = HttpClients.createDefault();

        // 創(chuàng)建post方式請(qǐng)求對(duì)象
        HttpPost httpPost = new HttpPost(url);

        // 生成請(qǐng)求參數(shù)
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        // 將參數(shù)添加到post請(qǐng)求中
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, charset));

        // 發(fā)送請(qǐng)求,獲取結(jié)果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);

        // 獲取響應(yīng)實(shí)體
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 按指定編碼轉(zhuǎn)換結(jié)果實(shí)體為String類型
            responseEntity = EntityUtils.toString(entity, charset);
        }

        // 釋放資源
        EntityUtils.consume(entity);
        response.close();

        return responseEntity;
    }
}

Freemarker工具類

package com.mosband.genecharts.util;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerUtil {
    private static final String path = FreemarkerUtil.class.getClassLoader().getResource("").getPath();

    public static String generateString(String templateFileName, String templateDirectory, Map<String, Object> datas)
            throws IOException, TemplateException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);

        // 設(shè)置默認(rèn)編碼
        configuration.setDefaultEncoding("UTF-8");

        // 設(shè)置模板所在文件夾
        configuration.setDirectoryForTemplateLoading(new File(path + templateDirectory));

        // 生成模板對(duì)象
        Template template = configuration.getTemplate(templateFileName);

        // 將datas寫(xiě)入模板并返回
        try (StringWriter stringWriter = new StringWriter()) {
            template.process(datas, stringWriter);
            stringWriter.flush();
            return stringWriter.getBuffer().toString();
        }
    }
}

生成Echarts工具類

package com.mosband.genecharts.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class EchartsUtil {
    private static String url = "http://localhost:6666";
    private static final String SUCCESS_CODE = "1";

    public static String generateEchartsBase64(String option) throws ClientProtocolException, IOException {
        String base64 = "";
        if (option == null) {
            return base64;
        }
        option = option.replaceAll("\\s+", "").replaceAll("\"", "'");

        // 將option字符串作為參數(shù)發(fā)送給echartsConvert服務(wù)器
        Map<String, String> params = new HashMap<>();
        params.put("opt", option);
        String response = HttpUtil.post(url, params, "utf-8");

        // 解析echartsConvert響應(yīng)
        JSONObject responseJson = JSON.parseObject(response);
        String code = responseJson.getString("code");

        // 如果echartsConvert正常返回
        if (SUCCESS_CODE.equals(code)) {
            base64 = responseJson.getString("data");
        }
        // 未正常返回
        else {
            String string = responseJson.getString("msg");
            throw new RuntimeException(string);
        }

        return base64;
    }
}

option.ftl

{
    title: {
        text:'${title}',
        x:'middle',
        textAlign:'center'
    },
    xAxis: {
        type: 'category',
        data: ${categories}
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: ${values},
        type: 'bar'
    }]
}

測(cè)試類

package com.mosband.genecharts;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

import org.apache.http.client.ClientProtocolException;

import com.alibaba.fastjson.JSON;
import com.mosband.genecharts.util.EchartsUtil;
import com.mosband.genecharts.util.FreemarkerUtil;

import freemarker.template.TemplateException;
import sun.misc.BASE64Decoder;

public class App {
    public static void main(String[] args) throws ClientProtocolException, IOException, TemplateException {
        // 變量
        String title = "水果";
        String[] categories = new String[] { "蘋(píng)果", "香蕉", "西瓜" };
        int[] values = new int[] { 3, 2, 1 };

        // 模板參數(shù)
        HashMap<String, Object> datas = new HashMap<>();
        datas.put("categories", JSON.toJSONString(categories));
        datas.put("values", JSON.toJSONString(values));
        datas.put("title", title);

        // 生成option字符串
        String option = FreemarkerUtil.generateString("option.ftl", "/com/mosband/genecharts/template", datas);

        // 根據(jù)option參數(shù)
        String base64 = EchartsUtil.generateEchartsBase64(option);
        
        System.out.println("BASE64:" + base64);
        generateImage(base64, "C:/Users/Administrator/Desktop/test.png");
    }

    public static void generateImage(String base64, String path) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        try (OutputStream out = new FileOutputStream(path)){
            // 解密
            byte[] b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out.write(b);
            out.flush();
        } 
    }
}

五、效果

控制臺(tái)打印結(jié)果
BASE64:iVBORw0KGgoAAAANSUhEUgAAA...
test.png

image.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • head插件安裝 1.準(zhǔn)備的資料https://download.csdn.net/download/wuzhua...
    ant_1024閱讀 1,191評(píng)論 0 0
  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個(gè) Awesome - XXX 系列...
    小邁克閱讀 3,124評(píng)論 1 3
  • 老師,非常謙虛,實(shí)際上你一直在喂平臺(tái)搭建平臺(tái),我們一起攜手共建,今日大平臺(tái), 善林媽媽,我請(qǐng)教一個(gè)問(wèn)題,聽(tīng)說(shuō)你們中...
    蘭香_e21a閱讀 278評(píng)論 0 0
  • 2月22日,在度過(guò)連續(xù)14天與雨相伴的天氣后,迎來(lái)了久違的朝陽(yáng)。蔣湖農(nóng)場(chǎng)服務(wù)企業(yè)用工現(xiàn)場(chǎng)招聘會(huì)在蔣湖農(nóng)場(chǎng)三江社...
    周波明閱讀 1,229評(píng)論 0 2
  • 前天一早,我跟先生說(shuō):看看我的手機(jī)吧!內(nèi)存都已經(jīng)百分之八十多了!把照片視頻導(dǎo)出來(lái)好嗎? 老先生心情還可以,接過(guò)去開(kāi)...
    天父公主閱讀 653評(píng)論 1 4

友情鏈接更多精彩內(nèi)容