直接上代码
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); 
 
 
                















![【Golang】Golang进阶系列教程--为什么 Go 不支持 []T 转换为 []interface](https://img-blog.csdnimg.cn/d248e8f19b51463297f721a2641fc471.png)

