#天天复制,今天写一个# 把文字转为图片

文字转图片的Java实现
本文介绍了一种将文本内容转换为图片的Java方法,包括设置字体大小、宽度、高度等参数,并通过BufferedImage和Graphics2D进行绘制,最终保存为jpg格式文件。
/**
     * 把文字转为图片
     * 
     * @param text
     *            要写的内容
     * @throws IOException
     */
    public static void textToImg(String text) throws IOException {
        int len = text.length();
        int fontSize = 1000;
        int width = len * fontSize;
        Font font = new Font("楷体", Font2D.NATIVE_RANK, fontSize);
        FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
        int height = fm.getHeight();// 获得字的高度
        System.out.println(height);
        BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffer.createGraphics();
        g.setBackground(Color.red);
        g.clearRect(0, 0, width, height);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形。此操作不使用当前绘图模式。 如果不加这一段,背景会一直是黑色(默认色)
        g.setFont(font);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1));//设置文字透明度
        g.setColor(new Color(Integer.parseInt("000000", 16)));
        g.drawString(text, 0, height - fontSize / 5);//把字的高度减去字体的五分之一,基本可以保持居中
        g.dispose();
        File file = new File("C://2.jpg");
        ImageIO.write(buffer, "jpg", file);//保存
}

 

转载于:https://www.cnblogs.com/xusir/p/3319802.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值