静态方法 直接调用
public static ByteArrayOutputStream createFontImage(String str, java.awt.Font font, Integer width, Integer height) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
g.setClip(0, 0, width, height);
g.setColor(java.awt.Color.white);//先用白色填充整张图片
g.fillRect(0, 0, width, height);
g.setColor(java.awt.Color.black); //设置黑色字体
FontDesignMetrics metrics = FontDesignMetrics.getMetrics((java.awt.Font) font);
// 设置画笔字体
g.setFont((java.awt.Font) font);
int strWidth = metrics.stringWidth(str);
int strHeight = metrics.getHeight();
int top = (height - strHeight) / 2 + metrics.getAscent();//上下居中
int left = (width - strWidth) / 2; //左右居中
g.drawString(str, left, top); // 填充字符串
g.dispose();
//将图片输出到ByteArrayOutputStream中
try {
ImageIO.write(image, "png", os);
} catch (IOException e) {
System.out.printf("IOException:%s", e);
}
return os;
}
使用的时日期的格式调用
public static void getDateInputStream(String sDate,String uuid) throws IOException, ParseException {
String newFilePath = System.getProperty("java.io.tmpdir") + File.separator + uuid + ".png";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String format = simpleDateFormat.format(new SimpleDateFormat("yyyy-MM-dd").parse(sDate.substring(0,10)));
java.awt.Font font = new java.awt.Font("宋体", 1,45);
// final String format = (new SimpleDateFormat("yyyy/MM/dd HH:mm")).format(date);
// java.awt.Font font = new java.awt.Font("宋体", 1,40);
ByteArrayOutputStream fontImage = createFontImage(format, font, 320, 120);
ByteArrayInputStream fis = new ByteArrayInputStream(fontImage.toByteArray());
FileUtils.copyToFile(fis, new File(newFilePath));
}