根据指定文字生成图片

时间:2023-02-10 22:42:43

这里是应用的play framework 1.2.x 各位大大可以根据自己的环境应用

 public static void show() {
try {
new Application().createImage("中华人名*",new Font("黑体",Font.BOLD,18),new File("D:\\a.png"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
render();
}
//根据str,font的样式以及输出文件目录
public void createImage(String str,Font font,File outFile) throws Exception{
//获取font的样式应用在str上的整个矩形
Rectangle2D r=font.getStringBounds(str, new FontRenderContext(AffineTransform.getScaleInstance(1, 1),false,false));
int unitHeight=(int)Math.floor(r.getHeight());//获取单个字符的高度
//获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
int width=(int)Math.round(r.getWidth())+1;
int height=unitHeight+3;//把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
//创建图片
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics g=image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);//先用白色填充整张图片,也就是背景
g.setColor(Color.black);//在换成黑色
g.setFont(font);//设置画笔字体
g.drawString(str, 0, font.getSize());//画出字符串
g.dispose();
ImageIO.write(image, "png", outFile);//输出png图片
}

访问调用方法, 看指定目录下 生成了指定文字的图片!