只是从代码实现层面说明,记录一次实现的过程
方法说明
先声明一个BufferedImage对象:
private BufferedImage image;
public void graphicsGeneration(List<JSONObject> list,String screenType,String savePath,String saveName){}
graphicsGeneration()参数说明:
list要输入的文字对象,以JSON格存储,示例:
JSONObject json = new JSONObject(); json.put("content","hello"); json.put("minute", Integer.valueOf(9)); json.put("color", Integer.valueOf(2)); json.put("fontStyle", Integer.valueOf(0)); json.put("fontType", Integer.valueOf(3)); json.put("fontSize", "18");
screenType是要传入的图片的尺寸大小,
- savePath是图片的存储位置,
- saveName是图片的名称(图片的后缀名.png or .jpg …)
实例化image,按照传入的图片尺寸,获取图片对象的上下文,进行图片的设置。
this.image = new BufferedImage(width,height,1); GraphicsD gd = this.image.createGraphics(); gd.setColor(new Color(0)); //图片为黑色 gd.dispose();
基本的图片完成,添加一些文字。进行基础设置:
Graphics2D gd2 = this.image.createGraphics(); gd.setColor(new Color(65280)); Font font = new Font(fontType,fStyle,fontSize); //字体的类型,样式,大小 gd.setFont(font); if((fontStyle.intValue()==4||(fontStyle.intValue()==8))){ Map<TextAttribute,Object> map = new Hashtable(); if(fontStyle.intValue()==4){ map.put(TextAttribute.UNDERLINE,TextAttribute.UNDERLINE_ON); }else{ map.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); } font = font.deriveFont(map); }
在图片设置字体
FontMetrics fm = gd.getFontMetric(font); int textWidth = fm.stringWidth("hello"); gd.drawString("hello",width.intValue()-textWidth,fontSize);
draw()方法中,要输入的文字,位置(x,y)。(“hello”,0,0)左上方开始,实例中从右上方开始。
输出图片保存在在指定位置,文件的输出流(FileOutputStream),BufferedOuputStream
public void createImage(String fileLocation,String saveSame ){ BufferedOutputStream bos =null; ... //检查文件路径是否存在,不存在则创建。 FileOutputStream fos = new FileOutputStream(fileLocation+"/"+saveName); bos = new BufferedOutputStream(fos); ImageIO.write(this.image,"png",bos); }
ImageIO .write();方法生成图片。传入image对像。
图片的绘制,注意图层,Graphics2D gd; 一个图层绘制完,gd.dispose(); 调用这个方法,禁止后面的程序中在使用。
还需要在查看文档,对于方法的参数在了解了解。再补充说明方法的作用。