文字转成图片

 写道
public static void create(String str, String filePath, Font font, Color color, int width, int height)
{
File file = new File(filePath);

BufferedImage bi = new BufferedImage(width, height,
1);

Graphics2D g2 = (Graphics2D)bi.getGraphics();

bi = g2.getDeviceConfiguration().createCompatibleImage(width, height, 3);
g2.dispose();
g2 = bi.createGraphics();

g2.setFont(font);
g2.setPaint(color);
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(str, context);
double x = (width - bounds.getWidth()) / 2.0D;
double y = (height - bounds.getHeight()) / 2.0D;
double ascent = -bounds.getY();
double baseY = y + ascent;

g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.drawImage(bi, 0, 0, null);

g2.drawString(str, (int)x, (int)baseY);

g2.dispose();
try {
ImageIO.write(bi, "png", file);
} catch (IOException e) {
e.printStackTrace();
}

}
public static void main(String[] args)
{
String fileName = System.currentTimeMillis() + ".png";
Font font = new Font("黑体", 1, 25);
test.create(""+"测试", "c://" + fileName, font, new Color(0, 0, 0), 500, 48);
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值