java 后台生成echarts base64图片 base64码

注意编码使用utf8

package com.core;

public interface GenBase64Service {

	public String gen(String options, int width, int height, boolean isDeletedFile, int type);
}
package com.core;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.Properties;
import java.util.UUID;

import sun.misc.BASE64Encoder;

public class GenBase64 implements GenBase64Service {

	/**
	 * 配置文件路径
	 */
	private String configFilePath;
	/**
	 * 
	 */
	private String exePath;
	/**
	 * 
	 */
	private String jsPath;
	/**
	 * 
	 */
	private String genImgPath;
	/**
	 * 
	 */
	private String genJsonPath;

	public String getConfigFilePath() {
		return configFilePath;
	}

	public void setConfigFilePath(String configFilePath) {
		this.configFilePath = configFilePath;
	}

	public String getExePath() {
		return exePath;
	}

	public void setExePath(String exePath) {
		this.exePath = exePath;
	}

	public String getJsPath() {
		return jsPath;
	}

	public void setJsPath(String jsPath) {
		this.jsPath = jsPath;
	}

	public String getGenImgPath() {
		return genImgPath;
	}

	public void setGenImgPath(String genImgPath) {
		this.genImgPath = genImgPath;
	}

	public String getGenJsonPath() {
		return genJsonPath;
	}

	public void setGenJsonPath(String genJsonPath) {
		this.genJsonPath = genJsonPath;
	}

	public GenBase64(String configFilePath) {
		this.setConfigFilePath(configFilePath);

		try {
			Properties properties = new Properties();
			BufferedReader bufferedReader = new BufferedReader(new FileReader(this.getConfigFilePath()));
			properties.load(bufferedReader);
			// 获取key对应的value值
			this.setExePath(properties.getProperty("phantomjs_path"));
			this.setJsPath(properties.getProperty("echarts_convert_path"));
			this.setGenImgPath(properties.getProperty("gen_img_path") + "\\");
			this.setGenJsonPath(properties.getProperty("gen_img_path") + "\\");
			System.out.println(this.toString());
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "[" + "configFilePath:" + this.getConfigFilePath() + ",exePath:" + this.getExePath() + ",jsPath:"
				+ this.getJsPath() + ",genImgPath:" + this.getGenImgPath() + ",genJsonPath:" + this.getGenJsonPath()
				+ "]";
	}

	@Override
	public String gen(String options, int width, int height, boolean isDeletedFile, int type) {
		String base64 = exec(options, width, height, isDeletedFile, type);
		return base64;
	}

	/**
	 * 
	 * @param options       json数据
	 * @param width         宽度
	 * @param height        高度
	 * @param isDeletedFile 生成完毕是否删除图片
	 * @param type          转换后的编码没有头,需要在保存时手动添加“data:image/png;base64,”,如不需要,即不做调整
	 *                      1返回带有“data:image/png;base64,” 其余不包含
	 * @return
	 */
	public String exec(String options, int width, int height, boolean isDeletedFile, int type) {
		String fileName = "test-" + UUID.randomUUID().toString().substring(0, 8) + ".png";
		String jsonPath = writeFile(options);
		String imgPath = this.getGenImgPath() + fileName;
		String cmd = "";
		if (width != 0 && height != 0) {
			cmd = this.getExePath() + " " + this.getJsPath() + " -infile " + jsonPath + " -outfile " + imgPath
					+ " -width " + width + " -height " + height;
		} else {
			cmd = this.getExePath() + " " + this.getJsPath() + " -infile " + jsonPath + " -outfile " + imgPath;
		}
		System.out.println(cmd);
		try {
			Process process = Runtime.getRuntime().exec(cmd);
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = "";
			while ((line = input.readLine()) != null) {
				System.out.println(line);
			}
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			String base64code = img2base64(imgPath, type);
			if (isDeletedFile) {
				deleteFile(imgPath);
			}
			//deleteFile(jsonPath);
			return base64code.replaceAll("\\s*", "");
		}
	}

	/**
	 * 转换后的编码没有头,需要在保存时手动添加“data:image/png;base64,”,如不需要,即不做调整
	 * 
	 * @param type    1返回带有“data:image/png;base64,” 其余不包含
	 * @param imgPath
	 * @return
	 */
	private static String img2base64(String imgPath, int type) {
		byte[] data = null;
		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgPath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		// 返回Base64编码过的字节数组字符串
		String result = encoder.encode(Objects.requireNonNull(data));
		if (type == 1) {
			StringBuffer sb = new StringBuffer();
			sb.append("data:image/png;base64,").append(result);
			return sb.toString();
		} else {
			return result;
		}

	}

	public static boolean deleteFile(String pathname) {
		boolean result = false;
		File file = new File(pathname);
		if (file.exists()) {
			file.delete();
			result = true;
			// System.out.println("文件已经被成功删除");
		}
		return result;
	}

	/*
	 * 
	 * options生成文件存储
	 */
	public String writeFile(String options) {
		String dataPath = this.getGenJsonPath() + UUID.randomUUID().toString().substring(0, 8) + ".json";
		try {
			/* option写入文本文件 用于执行命令 */
			File writename = new File(dataPath);
			if (!writename.exists()) {
				File dir = new File(writename.getParent());
				dir.mkdirs();
				writename.createNewFile(); //
			}
			BufferedWriter out = new BufferedWriter(new FileWriter(writename));
			out.write(options);
			out.flush(); // 把缓存区内容压入文件
			out.close(); // 最后关闭文件
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataPath;
	}

}
package com.core;

public class GenBase64Factory {

	private final static GenBase64Factory instance = new GenBase64Factory();

	public GenBase64Factory() {

	}

	public static GenBase64Factory getFactory() {
		return instance;
	}

	public GenBase64Service getGen(String configFilePath) {
		return new GenBase64(configFilePath);
	}

	
}

配置文件

phantomjs_path=D:\\tool\\phantomjs-1.9.2-windows\\phantomjs.exe
echarts_convert_path=D:\\tool\\echartsconvert\\echarts-convert.js
gen_img_path=D:\\gen

工具包 后续上传

https://download.csdn.net/download/Zaric_001/13963336

测试代码

/**
     * 注意UTF8编码
     * @param args
     */
    public static void main(String[] args) {
        String passcount = "1", unpasscount = "2", unapplycount = "3";
        StringBuffer sb = new StringBuffer();
        sb.append("{\"title\":{\"text\":\"销售图\",\"subtext\":\"销售统计\",\"x\":\"CENTER\"},\"toolbox\": {\"feature\": {\"saveAsImage\": {\"show\": true,}}},\"tooltip\": {\"show\": true},\"legend\": {\"data\":[\"直接访问\",\"邮件营销\",\"联盟广告\",\"视频广告\",\"搜索引擎\"]}, \"series\":[{\"name\":\"访问来源\",\"type\":\"pie\",\"radius\": '55%',\"center\": ['50%', '60%'],\"data\":[{\"value\":335, \"name\":\"直接访问\"},{\"value\":310, \"name\":\"邮件营销\"},{\"value\":234, \"name\":\"联盟广告\"},{\"value\":135, \"name\":\"视频广告\"},{\"value\":1548, \"name\":\"搜索引擎\"}]}]}");

        GenBase64Service genBean = GenBase64Factory.getFactory().getGen(
                "config.properties");
        String result = genBean.gen(sb.toString(), 1680, 500, false, 0);
        System.out.println(result);
    }

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值