`

文字转成图片

    博客分类:
  • java
 
阅读更多

 写道
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);
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics