java 生成文字图片的示例代码
本文主要介绍了java生成文字图片的示例代码,分享给大家,具体如下:
importjava.awt.Color; importjava.awt.Font; importjava.awt.FontMetrics; importjava.awt.Graphics; importjava.awt.Rectangle; importjava.awt.image.BufferedImage; importjava.io.File; importjavax.imageio.ImageIO; publicclassFontImage{ publicstaticvoidmain(String[]args)throwsException{ createImage("请A1003到3号窗口",newFont("宋体",Font.BOLD,30),newFile( "e:/a.png"),4096,64); createImage("请A1002到2号窗口",newFont("黑体",Font.BOLD,35),newFile( "e:/a1.png"),4096,64); createImage("请A1001到1号窗口",newFont("黑体",Font.PLAIN,40),newFile( "e:/a2.png"),4096,64); } //根据str,font的样式以及输出文件目录 publicstaticvoidcreateImage(Stringstr,Fontfont,FileoutFile, Integerwidth,Integerheight)throwsException{ //创建图片 BufferedImageimage=newBufferedImage(width,height, BufferedImage.TYPE_INT_BGR); Graphicsg=image.getGraphics(); g.setClip(0,0,width,height); g.setColor(Color.black); g.fillRect(0,0,width,height);//先用黑色填充整张图片,也就是背景 g.setColor(Color.red);//在换成黑色 g.setFont(font);//设置画笔字体 /**用于获得垂直居中y*/ Rectangleclip=g.getClipBounds(); FontMetricsfm=g.getFontMetrics(font); intascent=fm.getAscent(); intdescent=fm.getDescent(); inty=(clip.height-(ascent+descent))/2+ascent; for(inti=0;i<6;i++){//2563400680 g.drawString(str,i*680,y);//画出字符串 } g.dispose(); ImageIO.write(image,"png",outFile);//输出png图片 } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。