JAVA-字符串生成图片

直接上代码

public static void main(String[] args) throws IOException {
        createFontImage("红色", new Font("宋体", Font.BOLD, 50), 400, 400);
    }

    /**
     * 根据str,font的样式将文字变成图片,然后返回一个流
     *
     * @param str    字符串
     * @param font   字体
     * @param width  宽度
     * @param height 高度
     */
    public static ByteArrayOutputStream createFontImage(String str, Font font, Integer width, Integer height) throws IOException {
        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(Color.white);//先用白色填充整张图片,也就是背景
        g.fillRect(0, 0, width, height);
        g.setColor(Color.black); //在换成黑色
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        // 设置画笔字体
        g.setFont(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);
            org.apache.commons.io.FileUtils.writeByteArrayToFile(new File("E:\\temp\\a.png"), os.toByteArray());

        } catch (IOException e) {
            System.out.printf("IOException:%s", e);
            os.close();
            //StreamClose.close(os);//出了异常则在内部关闭流,StreamClose是我自己写的关闭流的工具
        }
        return os;
    }

 OK,直接搞定,如果是要返回图片或者存储图片,直接取就行

byte[] imgByte = os.toByteArray();
String img = FileUtils.base64EncodeString(imgByte);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值