java中文字生成图片

只是从代码实现层面说明,记录一次实现的过程

方法说明

先声明一个BufferedImage对象:

private BufferedImage image;
public void graphicsGeneration(List<JSONObject> list,String screenType,String savePath,String saveName){}
  1. 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 …)
  2. 实例化image,按照传入的图片尺寸,获取图片对象的上下文,进行图片的设置。

    this.image = new BufferedImage(width,height,1);
    GraphicsD gd = this.image.createGraphics();
    gd.setColor(new Color(0));  //图片为黑色
    gd.dispose();
    
  3. 基本的图片完成,添加一些文字。进行基础设置:

    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);
    }
    
  4. 在图片设置字体

        FontMetrics fm = gd.getFontMetric(font);
        int textWidth = fm.stringWidth("hello");    
        gd.drawString("hello",width.intValue()-textWidth,fontSize);

    draw()方法中,要输入的文字,位置(x,y)。(“hello”,0,0)左上方开始,实例中从右上方开始。

  5. 输出图片保存在在指定位置,文件的输出流(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(); 调用这个方法,禁止后面的程序中在使用。


还需要在查看文档,对于方法的参数在了解了解。再补充说明方法的作用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

heroboyluck

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值