将数据内容转化为图片
public class WqcTestController {
public static void createImage(String fileLocation, BufferedImage image) {
try {
FileOutputStream fos = new FileOutputStream(fileLocation);
BufferedOutputStream bos = new BufferedOutputStream(fos);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
bos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void graphicsGeneration(String path, List<Map> list) {
int imageWidth = 500;// 图片的宽度
int imageHeight = 500;// 图片的高度
BufferedImage image = new BufferedImage(imageWidth, imageHeight,BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.setColor(Color.white);
graphics.fillRect(0, 0, imageWidth, imageHeight);
graphics.setColor(Color.BLACK);
int high = 30;
int wigth = 0;
graphics.setFont(new Font("宋体", Font.BOLD, 30));
graphics.drawString("药方详情", 200, high);
graphics.setFont(new Font("宋体", Font.BOLD, 20));
high += 10;
graphics.drawLine(0, high, 550, high);
for(Map<String, String> rowMap : list){
high += 50;
wigth = 40;
for(Map.Entry<String, String> entry : rowMap.entrySet()){
String name = entry.getKey() + ":" + entry.getValue();
if("title".equals(entry.getKey())){
high += 30;
graphics.setFont(new Font("黑体", Font.BOLD, 20));
graphics.drawString(entry.getValue(), wigth, high);
graphics.setFont(new Font("宋体", Font.BOLD, 20));
} else {
graphics.drawString(name, wigth, high);
wigth += 160;
}
}
}
createImage(path,image);
}
/** 图片名生成 **/
public static String genImageName() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//加上三位随机数
Random random = new Random();
int end3 = random.nextInt(999);
//如果不足三位前面补0
String str = millis + String.format("%03d", end3);
return str;
}
public static void main(String[] args) {
List<Map> list = new ArrayList<Map>();
for (int i = 0; i < 8; i++) {
Map<String, String> mapTitle = new HashMap<String, String>();
mapTitle.put("单价/克", "20.0");
mapTitle.put("克数", "1");
mapTitle.put("名称", "柴胡");
list.add(mapTitle);
}
String path = "E:/upload/image";
File newFileDir = new File(path);
//如果不存在 则创建
if (!newFileDir.exists()) {
newFileDir.mkdirs();
}
graphicsGeneration(path+"/"+genImageName()+".jpg",list);
System.out.println("完成");
}
}