Java指定字符串生成图片,生成时间戳图片,同时保存在系统临时路径

 静态方法 直接调用

    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));
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不想看海

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

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

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

打赏作者

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

抵扣说明:

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

余额充值