Java用BufferedImage和Graphics画图。

问题:网上大部分内容重复,且描述简单。注:内容:将某个字生成图片,且对图片背景色和图片上字的颜色有要求的情况。

解决:先用Graphics的方法setColor设置一下颜色,然后再用该类的fillRect填充背景色,接着再用该类的setColor设置一下颜色,再接着就是用该类的drawString画字了。ImageIO.write输出图片。最后用该类的dispose释放资源。

局部代码:

int imageWidth = 200;
int imageHeight = 200;
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
int fontSize = 100;
Font font = new Font("楷体", Font.PLAIN, fontSize);
graphics.setFont(font);
graphics.setColor(new Color(246, 96, 0));
graphics.fillRect(0, 0, imageWidth, imageHeight);
graphics.setColor(new Color(255, 255, 255));
int strWidth = graphics.getFontMetrics().stringWidth("好");
graphics.drawString("好", fontSize - (strWidth / 2), fontSize + 30);
ImageIO.write(image, "PNG", new File("D:\\abc.png"));
graphics.dispose();

posted @ 2015-06-04 13:31  (;)  阅读(2773)  评论(0编辑  收藏  举报