读取本地json文件
/**
* 读取json文件,返回json串
* @param fileName
* @return
*/
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
JSONObject jo = JSON.parseObject(jsonStr);
通过json获取图片的width,heightd数据。
BufferedImage bi = new BufferedImage(Integer.valueOf(width), Integer.valueOf(height), BufferedImage.TYPE_INT_RGB);// INT精确度达到一定,RGB三原色,高度70,宽度150 // 得到图片缓冲区
Graphics2D g2 = (Graphics2D) bi.getGraphics(); // 得到它的绘制环境(这张图片的笔)
g2.drawImage(back1bg.getScaledInstance(width, height, Image.SCALE_DEFAULT), 0, 0, null);
JSONArray data = JSON.parseArray(jo.get("data").toString());
int size = data.size();
for (int i = 0; i < size; i++) {
JSONObject jsonObject = (JSONObject) JSON.parse(data.get(i).toString());
g2.setColor(Color.getColor(jsonObject.get("color").toString()));// 设置字体颜色
g2.setFont(new Font("微软雅黑", Font.BOLD, Integer.parseInt(jsonObject.get("fontsize").toString().replace("px",""))));
g2.drawString(jsonObject.get("text").toString().replace(" "," "), Integer.parseInt(jsonObject.get("left").toString()), Integer.parseInt(jsonObject.get("top").toString()));
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//消除文字锯齿
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //消除画图锯齿
}
g2.dispose(); // 释放对象
ImageIO.write(bi, "JPEG", new FileOutputStream("D:/a.jpg"));// 保存图片 JPEG表示保存格式
如果要添加图片,一定是从先到后重叠。这里要注意了。