如何使用Java创建图像?
答
如果你已经有了一个图像文件或图像的URL,那么你可以使用Toolkit得到一个Image:
Image img = Toolkit . getDefaultToolkit() . createImage (filename);
如果您需要构建一个新的图像栅格和绘制成图像,然后就可以使用BufferedImage。您可以通过调用其createGraphics函数并在图形对象上绘画来绘制到BufferedImage上。要将BufferedImage保存到GIF中,可以使用ImageIO类写出图像。
答
,最好的办法是产生一个BufferedImage
:
BufferedImage img = new BufferedImage(int width, int height, int imageType)
// you can find the Types variables in the api
然后,生成该图像的Graphics2D,这个对象允许您设置一个背景,绘制形状:
Graphics2D g = img.createGraphics();
g.setBackground(Color color) ; //Find how to built this object look at the java api
g.draw(Shape s);
g.dispose(); //don't forget it!!!
要建立图像:
File file = new File(dir, name);
try{
ImageIO.write(img, "gif", file);
}catch(IOException e){
e.printStackTrace();
}
使用Toolkit阅读图像是一种过时的方式。 – Roman 2010-04-26 08:15:30
@罗曼,新方法是什么? – 2010-04-26 08:41:29